2009-09-22 186 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