This question already has an answer here:
My Worksheet has 29 rows and 39 columns. Currently I use
lrow = ActiveSheet.UsedRange.Rows.count
--> for getting used rows count
lColumn = ActiveSheet.UsedRange.Columns.count
--> for getting used columns count
Excel gives wrong count every time it runs. Sometimes it gives:
Rows: 29 Columns: 784
On other runs it gives
Rows: 32755 and Columns as: 784
and on other runs it gives different values.
I have checked there is no junk data after 29 rows and after 39 columns. Also,
Previous to filling the data I clear the sheet with: ActiveWorkbook.Worksheets("Field Difference").Cells.Delete
I hope ActiveWorkbook.Worksheets("Field Difference").Cells.Delete
completely clears the sheet and clears the sheet of the junk data if any on the sheet. How else I can make sure that there is no junk data in the worksheet.
I do understand that we have other Options such as:
ActiveWorkbook.Worksheets("Field Difference").UsedRange.ClearContents
- to clear only contents
ActiveWorkbook.Worksheets("Field Difference").UsedRange.Clear
- to clear formatting as well.
Please do let me know why I am getting wrong values for the count of rows and columns and what is the way out. Can I use any other reliable way to get the UsedRange
row count and UsedRange
columns count.
Worksheet layout can affect the .UsedRange and .CurrentRegion properties. For a definitive 'last cell' search backwards from A1 first by rows then by columns using a blanket wildcard.
Methods for finding the last populated cell for a given column(row) are well know. using
End(xlUp)
(End(xlToLeft)
) from the last cell of that column (row).To get the last cell of the actually populated region of a worksheet, you can use this custom function which will get it to you reliably:
By bringing the last cell, you can get the whole range from
A1
to that cell, usingOccasionally you might be interested in finding the populated region which is not starting at
A1
. You can, in this case, find Similarly the "Topleft" Cell of the actually populated region, using this custom function:finally, you can join the two cells to get the actually ppulated region, like this:
For Last Row and Column in Column A: