The simplest way to do it is
Set myrng1 = Range("B3:B" & LastRow)
Else if you want to follow your approach then as Bernard mentioned, use the .Address
property.
Change your code to
Set myrng1 = Range("B3:" & _
Cells(LastRow, 2).Address( _
rowabsolute:=False, _
columnabsolute:=False) _
)
or this which does the same thing.
Set myrng1 = Range("B3:" & _
Replace(Cells(LastRow, 2).Address, "$", "") _
)
Also I hope you have declared LastRow
as Long
and not as Integer
as you may get an overflow error in xl2007+
One last thing. Your Cells
object is not fully qualified which can give you error. Fully qualify them. For example (Notice the DOTS)
Set myrng1 = ThisWorkbook.Sheets("Sheet1").Range("B3:B" & LastRow)
or
With ThisWorkbook.Sheets("Sheet1")
Set myrng1 = .Range("B3:" & _
.Cells(LastRow, 2).Address( _
rowabsolute:=False, _
columnabsolute:=False) _
)
End With
EDIT Thanks to pnuts for pointing this out
Once you solve the above problem, you will face more problems. For example "=SUMIF(myrng1,RC[-1],myrng2)"
. Anything between the "
will be considered a string. You may want to use this instead
"=SUMIF(" & myrng1.Address & ",RC[-1]," & myrng2.Address & ")"
Again, you may want to use .Address
without the "$" as mentioned above.
One more thing. If row 30 is the lastrow
then you can fill the formula in all the cells in one go instead of using AutoFill
See this Example
With ThisWorkbook.Sheets("Sheet1")
.Range("B15:B30").Formula = "=SUMIF(" & _
myrng1.Address & _
",A15," & _
myrng2.Address & ")"
End With
Or
With ThisWorkbook.Sheets("Sheet1")
.Range("B15:B" & lastrow).Formula = "=SUMIF(" & _
myrng1.Address & _
",A15," & _
myrng2.Address & ")"
End With
Furthermore, I would like to draw your attention to this INTERESTING READ :p