循环浏览Excel中范围的每一行


Answers:


150
Dim a As Range, b As Range

Set a = Selection

For Each b In a.Rows
    MsgBox b.Address
Next

149

像这样:

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

8

刚偶然发现这一点,以为我会建议我的解决方案。我通常喜欢使用将范围分配给多维数组的内置功能(我想我也是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中处理数据的一种非常有效的方法。


我最喜欢这种方式!
athos

2
支持它的两个主要优点是:1)数组方法总是比遍历一个范围,2)它很简单,您可以在两个方向上使用它,并在进行一些计算后写回数组:Range("A1:D4") = myarray注意: Dim myarray作为变体;注意以下事实:默认情况下它是一个基于 1d的2dim数组
TM

7

在循环中,我总是更喜欢使用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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.