I'm trying to streamline the code of a VBA project in Excel and I run into a problem when setting a range:
Sub Test()
Dim lRow As Long, lCol As Long
Dim TSheet As Variant, TSheets As Variant
Dim rng As Range
TSheets = Array("Sheet1", "Sheet2", "Sheet3")
For Each TSheet in TSheets
lRow = ThisWorkbook.Sheets(TSheet).Cells(Rows.Count, "B").End(xlUp).Row + 1
lCol = ThisWorkbook.Sheets(TSheet).Cells(lRow - 1, "B").End(xlToRight).Column
Set rng = ThisWorkbook.Sheets(TSheet).Range(Cells(2, 2), Cells(lRow, lCol))
Next TSheet
End Sub
I get Error 1004 "Application-defined or object-defined error". Set rng = ThisWorkbook.Sheets(TSheet).Cells(lRow, lCol)
works, so there must be a problem with the Range(Cells(),Cells())
syntax. Could you help me with that?
edit: Thanks to GSerg (thanks a lot!) I got it to work, the key is I have to write Set rng = ThisWorkbook.Sheets(TSheet).Range(ThisWorkbook.Sheets(TSheet).Cells(2, 2), ThisWorkbook.Sheets(TSheet).Cells(lRow, lCol))
. However, I still don't get why my original code got an error message. Shouldn't cells()
automatically refer to the single sheet I am working on?