在Excel中计数行

我想要一个for循环遍历excel电子表格上列b的填充部分。 我几乎肯定我有代码正确,但由于某种原因,它给了我一个无效的限定符错误在下面的代码.Row点。 我真的不确定我哪里错了,任何帮助将不胜感激。

 Set rng1 = Range("B2") Set rng2 = Range("B2").End(xlDown) For i = 1 To Sheet2.Range(rng1, rng2).Row.Count 

你快到了:

 .Rows.Count 

更新

尝试这个:

 Dim lLastRow As Long lLastRow = Sheet2.Range("B2").End(xlDown).Row For i = 1 To lLastRow Debug.Print Sheet2.Cells(i, 1) Next 

许多方法来做到这一点,这里是一个:

 Option Explicit Sub Rowcount() Dim i& , LastRow& Dim Sh as Worksheet Set Sh= thisworkbook.sheets("Sheet2") with Sh 'Set rng1 = .Range("B2") Set rng2 = .Range("B2").End(xlDown) 'this method gives the first empty cell, wich is not always the last Row , works if NO empty cell lastRow = rng2.row ' the real last row with some empty cells is LastRow= .cells(.rows.count,2).end(xlup).row For i = 1 To LastRow ...'do stuff 'Debug.Print .Cells(i, 1).value2 Next i End With 'Sh 

结束小组

您还可以使用查找填充数据的最后一行

 Sub lastRowTest() Dim lastRow As Integer Dim i As Integer 'edit: Patrick Lepelletier also mentions this method in his post lastRow = Worksheets("Sheet1").Range("B65536").End(xlUp).Row 'finds the first non-empty cell, starting from the bottom For i = 1 To lastRow 'do stuff on cells Next i End Sub