I have written a simple code to illustrate my predicament.
Sub test() Dim sh As Worksheet Set sh = ThisWorkbook.Sheets("Sheet1") Dim k As Long k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count End Sub
What happens is this: We count the rows which contain values starting at A1. If the number of rows which contain values is > 1 the code works great. However, if A1 is the only cell which contains any value, k = 1,048,576 which I guess is the maximum number of rows allowed in Excel.
Why doesn't k = 1?
Pictures:
EDIT: The workaround that I'm using is the following:
Sub test() Dim sh As Worksheet Set sh = ThisWorkbook.Sheets("Sheet1") Dim k As Long k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count If k = 1048576 Then k = 1 End If MsgBox (k) End Sub
Since k is always equal to 1048576 when the number of rows with values is 1. It just feels a bit silly having to do something like this.
To count rows using VBA, you need to define the range from which you want to count the rows and then use the count and rows property to get the count of the row from that range. You can also use a loop to count rows where you have data only.
To count rows. Depending on the circumstance, you can use the COUNTA, COUNT, COUNTBLANK, or COUNTIF functions. read more, we need to make use of RANGE object, in this object, we need to use the ROWS object, and in this, we need to use COUNT property.
Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count. Do the same thing to count columns, but this time click the row selector at the left end of the row. If you select an entire row or column, Excel counts just the cells that contain data.
If you want to count only nonblank cells, you can use this formula =COUNTA(A1:G11) (the range A1:G11 indicates the range you want to count the nonblank cells from, you can change it as you need), or you also can use this formula =COUNTIF(A1:G11,"<>").
Probably a better solution is work upwards from the bottom:
k=sh.Range("A1048576").end(xlUp).row
You should use UsedRange
instead like so:
Sub test() Dim sh As Worksheet Dim rn As Range Set sh = ThisWorkbook.Sheets("Sheet1") Dim k As Long Set rn = sh.UsedRange k = rn.Rows.Count + rn.Row - 1 End Sub
The + rn.Row - 1
part is because the UsedRange only starts at the first row and column used, so if you have something in row 3 to 10, but rows 1 and 2 is empty, rn.Rows.Count
would be 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With