Runtime error 1004, method range of object _worksheet failed. Defining ranges in VBA

60 Views Asked by At

I am defining some column ranges in VBA so that I can easily use the name of a range later instead of defining every time. There are multiple worksheets in my workbook, which is why I'm defining the worksheet. I get "Runtime error 1004: method range of object _worksheet failed, and debug highlights this line:

Set PlateIDRng = Master.Range("A2", Range("A2").End(xlDown))

This is the whole code:

Sub defineRanges()

Dim WB As Workbook
Dim Master As Worksheet

Set WB = ThisWorkbook
Set Master = Worksheets("All_Plates_Mastersheet")

Dim PlateIDRng As Range
Dim ClientRng As Range
Dim ProjIDRng As Range
Dim PriorityRng As Range
Dim LimsStepRng As Range
Dim NumSamplesRng As Range
Dim LenNumRng As Range
Dim PhysLocRng As Range
Dim DateRecRng As Range

Set PlateIDRng = Master.Range("A2", Range("A2").End(xlDown))
Set ClientRng = Master.Range("B2", Range("B2").End(xlDown))
Set ProjIDRng = Master.Range("C2", Range("C2").End(xlDown))
Set PriorityRng = Master.Range("D2", Range("D2").End(xlDown))
Set LimsStepRng = Master.Range("E2", Range("E2").End(xlDown))
Set NumSamplesRng = Master.Range("F2", Range("F2").End(xlDown))
Set LenNumRng = Master.Range("G2", Range("G2").End(xlDown))
Set PhysLocRng = Master.Range("H2", Range("H2").End(xlDown))
Set DateRecRng = Master.Range("I2", Range("I2").End(xlDown))

End Sub

I have tried structuring the 'last row' a few different ways but get the same error.

1

There are 1 best solutions below

3
kevin On

The error should only come up if you are running the code while Master is not the active sheet. The reason is that Range("A2").End(xlDown) is not qualified with a sheet, so it references the range on whatever sheet you have active. If you activate Master before that block of code, it should work. But the correct structure would be

Set PlateIDRng = Range(Master.Range("A2"), Master.Range("A2").End(xlDown))

And the neater format would be (note the . in front of .Range)

With Master
    Set PlateIDRng = .Range(.Range("A2"), .Range("A2").End(xlDown))
End With