2009-09-22 225 views
80

这是我确定有一个内置函数(以前我可能已经被告知它)的那些东西之一,但是我正在抓我的头脑要记住它。循环遍历Excel中的一个范围中的每一行

如何使用Excel VBA遍历多列范围的每一行?所有我一直在寻找了教程好像只提过一维范围内的工作...

回答

114
Dim a As Range, b As Range 

Set a = Selection 

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

事情是这样的:

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 
4

在循环中,我总是喜欢使用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来处理数据非常有力的方式。

+0

我最喜欢这种方式! – athos 2017-03-20 02:20:11

+0

支持它的两个主要优点:1)数组方法**总是比在一个范围内循环更快** 2)它很简单,您可以在**两个方向使用它**并在数组后面写入数组一些计算:'Range(“A1:D4”)= myarray'。 **注意:** Dim myarray'作为变体;请注意默认情况下它是* 1based * 2dim数组的事实 – 2017-10-08 12:56:46

相关问题