vba 如何在EXCEL VBA中获取行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21554059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:41:57  来源:igfitidea点击:

How to get the row count in EXCEL VBA

excel-vbavbaexcel

提问by Alwyn Miranda

I am developing a dashboard in excel. And I am looking for calculating row count. (How many records are present) ..

我正在用 excel 开发一个仪表板。我正在寻找计算行数。(存在多少条记录) ..

Since there are some blank cells I thought to go from bottom to up. I use the following

由于有一些空白单元格,我认为从下到上。我使用以下

   Range("A1048576").Select
Selection.End(xlUp).Select

After this execution the active cell is at A113 which means the row count is 113.

执行此操作后,活动单元格位于 A113,这意味着行数为 113。

My question is how to get this number 113 from the active cell?

我的问题是如何从活动单元格中获取这个数字 113?

回答by Dmitry Pavliv

You can use this:

你可以使用这个:

Dim lastrow as Long
lastrow = Cells(Rows.Count,"A").End(xlUp).Row

lastrowwill contain number of last empty row in column A, in your case 113

lastrow将包含列中最后一个空行的数量A,在您的情况下为 113

回答by Jim Simson

Here is what I usually use for that:

这是我通常使用的:

lastrow = WorksheetFunction.CountA(Columns("A:A"))

This will return the number of non-empty cells in Column "A" which is what I think you're after. Hope this helps.

这将返回列“A”中非空单元格的数量,这就是我认为您所追求的。希望这可以帮助。

回答by simpLE MAn

If there is a slight chance that the last row of the worksheet is not empty, you should add an IsEmpty()check to @simoco 's solution. Therefore; following is a function that returns the last used row and check if the last row of the worksheet is empty:

如果工作表的最后一行不是空的可能性很小,您应该IsEmpty()在@simoco 的解决方案中添加一个检查。所以; 以下是返回最后使用的行并检查工作表的最后一行是否为空的函数:

Function lastRow(WS As Worksheet, iColumn As String) As Long

    If Not IsEmpty(WS.Range(iColumn & WS.Rows.Count)) Then
        lastRow = WS.Rows.Count
    Else
        lastRow = WS.Range(iColumn & WS.Rows.Count).End(xlUp).Row
    End If

End Function