I want to write a simple function that tells me the column length, giving the first record of the column. Hence, I write something like…
Public Function getColumnLen(firstCell As Range) As Long
Dim lastRow As Long
lastRow = Range(firstCell.Address).End(xlDown).Row
getColumnLen = lastRow - firstCell.Row + 1
End Function
Now I have two worksheets in my project, “A” and “B” and in VBA I call
Dim colLen as Long
colLen = getColumnLen(Worksheets("A").Range("A1"))
when I want to know the height of data starting on A1. The resulting value of colLen depends on whether sheet “A” is active or “B” is active. The thing is that in the getColumnLen function, firstCell remembers that it is a part of “A” sheet, however scrolling is done on the active sheet. Is there any way to make this give correct results regardless of the active sheet, other than activating firstCell in each call?
It’s because you’re giving it a not-fully-qualified cell address:
Here,
firstCell.Addressreturns$A$1regardless of what worksheet you specify when you call the function.Worksheets("A").Range("A1").AddressWorksheets("B").Range("A1").AddressWorksheets("Whatever other sheet").Range("A1").AddressThese all return
$A$1!Forget about the
Addressproperty. If you want to know what it does, read VBA help. Just do this instead:Be advised, however, that this method of finding the last row will fail if you range contains blank cells. This issue has been addressed a gazillion times; just search this site but be aware that not all of the proposed solutions are equally valid!