vba 工作表中的行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11595816/
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 13:37:50  来源:igfitidea点击:

Amount of rows in sheet

excel-vbavbaexcel

提问by What'sUP

Goal:
A variable should contain amount of rows from a specific sheet.

目标:
变量应包含特定工作表中的行数。

Problem:
What syntax code in Excel VBA do I need to count amount of rows from sheet?

问题:
我需要在 Excel VBA 中使用哪些语法代码来计算工作表中的行数?

回答by Reafidy

Using the usedrange method is one of my favourites but it needs to be treated with care. It has a few flaws/gotchas. It is a known problem that excel does not keep track of the used range very well. Any reference to the used range via VBA will reset the value to the current used range. So try running this sub procedure when you are getting the used range:

使用 usedrange 方法是我的最爱之一,但需要谨慎对待。它有一些缺陷/问题。excel 不能很好地跟踪使用的范围是一个已知的问题。通过 VBA 对使用范围的任何引用都会将该值重置为当前使用的范围。因此,当您获得使用的范围时,请尝试运行此子过程:

Dim lRowCount as Long

Application.ActiveSheet.UsedRange
lRowCount = Worksheets("MySheet").UsedRange.Rows.Count

But be aware this will give you the usedrange count, so if you have blank rows at the top of your workbook (which often people do to leave space for things like filter criteria etc) then they will not be counted. The usedrange method can also be affected by formatting.

但请注意,这将为您提供已使用的范围计数,因此如果您的工作簿顶部有空白行(人们通常会这样做,以便为过滤条件等留出空间),那么它们将不会被计算在内。usedrange 方法也可能受格式影响。

If you want the last row used, which is what I think you want, then you can use the find method which is more reliable:

如果你想使用最后一行,这就是我认为你想要的,那么你可以使用更可靠的 find 方法:

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 atleast one cell with data in it, then you can simplify the above to:

如果您知道至少有一个包含数据的单元格,那么您可以将上述内容简化为:

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 regarding used range I spoke about above

关于我上面提到的使用范围,请参见此处

回答by UberNubIsTrue

You can also try:

你也可以试试:

i = Sheets("SheetName").UsedRange.Rows.Count

However, this can get a little buggy if you start deleting and clearing rows.

但是,如果您开始删除和清除行,这可能会出现一些问题。

A better way to do this is:

一个更好的方法是:

i = Cells(Sheets("SheetName").Rows.Count, 1).End(xlup).Row

This assumes that each row has data in column 1.

这假设每一行的第 1 列都有数据。