用于计算 VBA 中总行数的 Excel 文件

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

Excel file to count total rows in VBA

excelexcel-vbavba

提问by kumar chaudhari

I am writing a VBA macro to count the number of rows in sheet2of Excel file

我正在编写一个 VBA 宏来计算sheet2Excel 文件中的行数

Dim cnt As Integer 
Dim i As Integer

cnt = Range("Sheet2").Rows.Count ' giving error at this row
For i = 2 To cnt
    t1 = "A" + CStr(i)
    t2 = "B" + CStr(i)
Next i

But it giving error:

但它给出了错误:

Method 'Range' of object '_global' failed

对象“_global”的方法“Range”失败

回答by Arun Singh

Rangeis used for Cell Rangenot for Excel Sheets.

Range用于Cell Range而不是Excel Sheets

Try the followings:

请尝试以下操作:

  1. To get the count of used rows:

    cnt = Worksheets("Sheet2").Cells.SpecialCells(xlCellTypeLastCell).Row
    
  2. To get the count of all rows of the sheet:

    cnt = Worksheets("Sheet2").Rows.Count
    
  3. To get the count of rows of a specific Range:

    cnt = Worksheets("Sheet2").Range("A1:A6500").Rows.Count
    
  1. 获取已用行数

    cnt = Worksheets("Sheet2").Cells.SpecialCells(xlCellTypeLastCell).Row
    
  2. 要获取工作表所有行计数

    cnt = Worksheets("Sheet2").Rows.Count
    
  3. 要获取特定的行数Range

    cnt = Worksheets("Sheet2").Range("A1:A6500").Rows.Count
    

I think you are looking for used cell range. Define variables as Long to resolve the overflow issue

我认为您正在寻找使用过的单元格范围。将变量定义为 Long 以解决溢出问题

Dim cnt As Long 
Dim i As Long

回答by GSerg

Sheet2 is a sheet, not a range.

Sheet2 是一个工作表,而不是一个范围。

Worksheets("Sheet2").Rows.Count

回答by Colin Broadley

Try using the following code:

尝试使用以下代码:

Dim crb1 As Long


'Count Rows

    Range("B2").Select
    Selection.End(xlDown).Select
    crb1 = ActiveCell.Row

    MsgBox ("Number of rows are ") & Str(crb1)