17

This is kind of silly, but I've been stuck for a while in this simple statement:

    Dim range1 as Range
    Dim mysheet as String
    Dim myrange as String

    mysheet = "Sheet1"
    range = "A1:A10"

range1 = Worksheets(mysheet).Range(myrange)

I've testing all the solutions that I've found on the internet as for example this, this and this, but nothing.

All the time it gives me errors: 1004 "Error defined by the application" or "object variable or with not set".

I have tried the following:

range1 = ThisWorkbook.Worksheets(mysheet).Range(myrange)

range1 = ActiveWorkbook.Worksheets(mysheet).Range(myrange)

range1 = Sheets(mysheet).Range(myrange) (and the combinations above)

range1 = Worksheets(mysheet).Range(Cells(1,1), Cells(1,10)) (and the combinations with This/Active workbook)

and

with This/ActiveWorkbook
range1 = .Worksheets(mysheet).Range(myrange)
end with

None have worked.

This is a REALLY silly thing, but I've been stuck for a while now :s

Can anyone help me?

Really thanks in advance.

Best regards,

Community
  • 1
  • 1
Christian Vielma
  • 15,263
  • 12
  • 53
  • 60

2 Answers2

32

You need to use Set to assign objects:

Set range1 = Worksheets(mysheet).Range(myrange)
assylias
  • 321,522
  • 82
  • 660
  • 783
-1

I get that you were stuck and I offer a slight stuckness-variant:

rngStr = corrSht.Range("T" & 63 + iterCnt).Address               
*** Set strRng = Range(rngStr)***

So sure, **** use Set to have string 'become' a range... But that didn't work until I added "Address" to the range string in the preceding line. So hovvering the cursor over rngStr showed the range rather than the range content. I find VBA very cheeky/irritatio like this. Wish I had a better overview of the "why" as opposed to the "how to" sometimes....