Using the usedrange method is one of my favorites, but it should be handled with care. It has several drawbacks / gotchas. This is a known issue that excel does not track the used range very well. Any reference to the used range through VBA will reset the value of the current range. So try this helper procedure when you get the used range:
Dim lRowCount as Long Application.ActiveSheet.UsedRange lRowCount = Worksheets("MySheet").UsedRange.Rows.Count
But remember that this will give you the number of ranges used , so if you have blank lines at the top of your book (which often people do to leave room for things like filter criteria, etc.), then they donβt will be taken into account. Formatting may also affect the usedrange method.
If you want to use the last line, which I think you need, then you can use the more reliable find method:
Dim rLastCell As Range Dim lLastRow As Long Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False) If Not rLastCell Is Nothing Then lLastRow = rLastCell.Row
If you know that you have at least one cell with data in it, you can simplify this:
Dim lLastRow As Long lLastRow = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
See here for the range used, which I mentioned above
Reafidy
source share