【问题标题】:Count rows in excel计算excel中的行数
【发布时间】:2014-10-21 14:48:01
【问题描述】:

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

Set rng1 = Range("B2")
Set rng2 = Range("B2").End(xlDown)


For i = 1 To Sheet2.Range(rng1, rng2).Row.Count

【问题讨论】:

    标签: excel vba for-loop range


    【解决方案1】:

    你快到了:

    .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
    

    【讨论】:

    • 谢谢!我做了那个改变,但现在它说范围对象的方法失败了......
    • 我已经更新了我的答案,为您提供了一种不同的方法。您可以通过引用它们来操作单元格,如 debug.print 之后所示
    【解决方案2】:

    有很多方法可以做到这一点,这里有一个:

    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
    

    结束子

    【讨论】:

      【解决方案3】:

      您还可以使用

      找到填充数据的最后一行
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        相关资源
        最近更新 更多