【问题标题】:Loop through each row of a range in Excel循环遍历 Excel 中某个范围的每一行
【发布时间】:2010-11-30 14:21:51
【问题描述】:

这是我确信有一个内置函数的事情之一(我很可能在过去被告知过),但我正在抓耳挠腮地记住它。

如何使用 Excel VBA 循环遍历多列区域的每一行?我一直在搜索的所有教程似乎都只提到了通过一维范围工作......

【问题讨论】:

标签: excel vba loops excel-2003


【解决方案1】:

类似这样的:

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A1:C2")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
  Next cell
Next row

【讨论】:

    【解决方案2】:
    Dim a As Range, b As Range
    
    Set a = Selection
    
    For Each b In a.Rows
        MsgBox b.Address
    Next
    

    【讨论】:

      【解决方案3】:

      在 Loops 中,我总是喜欢使用Cells 类,使用 R1C1 引用方法,像这样:

      Cells(rr, col).Formula = ...
      

      这让我可以轻松快速地循环范围单元格:

      Dim r As Long
      Dim c As Long
      
      c = GetTargetColumn() ' Or you could just set this manually, like: c = 1
      
      With Sheet1 ' <-- You should always qualify a range with a sheet!
      
          For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)
      
              ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
              .Cells(r, c).Value = MyListOfStuff(r)
      
              '---- or ----
      
              '...to easily copy from one place to another (even with an offset of rows and columns)
              .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value
      
      
          Next r
      
      End With
      

      【讨论】:

        【解决方案4】:

        只是偶然发现了这一点,并认为我会提出我的解决方案。我通常喜欢使用将范围分配给多维数组的内置功能(我猜它也是我的 JS 程序员)。

        我经常这样写代码:

        Sub arrayBuilder()
        
        myarray = Range("A1:D4")
        
        'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned
        
        For i = 1 To UBound(myarray)
        
            For j = 1 To UBound(myarray, 2)
        
            Debug.Print (myarray(i, j))
        
            Next j
        
        Next i
        
        End Sub
        

        为变量分配范围是在 VBA 中操作数据的一种非常强大的方法。

        【讨论】:

        • 我最喜欢这种方式!
        • 支持它的两个主要优点:1) 数组方法总是比遍历范围更快,2) 它很简单,您可以在 两个方向并在一些计算后写回数组:Range("A1:D4") = myarray注意: Dim myarray 作为变体;注意它默认是一个1based 2dim 数组
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-14
        • 2016-01-22
        • 1970-01-01
        • 2013-08-17
        • 1970-01-01
        相关资源
        最近更新 更多