在Excel中循环遍历范围的每一行
这是其中的一件事,我肯定有一个内置的功能(我很可能在过去被告知),但我挠头记住它 如何使用Excel VBA循环遍历多列范围的每一行?我一直在搜索的所有教程似乎只提到在一维范围内工作…类似这样的内容:在Excel中循环遍历范围的每一行,excel,vba,loops,excel-2003,Excel,Vba,Loops,Excel 2003,这是其中的一件事,我肯定有一个内置的功能(我很可能在过去被告知),但我挠头记住它 如何使用Excel VBA循环遍历多列范围的每一行?我一直在搜索的所有教程似乎只提到在一维范围内工作…类似这样的内容: 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 Somethin
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
Cells(rr, col).Formula = ...
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
在循环中,我总是喜欢使用
Cells
类,使用R1C1引用方法,如下所示:
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
Cells(rr, col).Formula = ...
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
这使我能够快速轻松地在单元格范围内循环:
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
Dim r尽可能长
尺寸c与长度相同
c=GetTargetColumn(),或者您可以手动设置它,如:c=1
在Sheet1'中,我偶然发现了这一点,并认为我会提出我的解决方案。我通常喜欢使用内置的功能,将一个范围分配给一个多维数组(我想我也是JS程序员)
我经常编写这样的代码:
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
Cells(rr, col).Formula = ...
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
作为变体;请注意,默认情况下它是一个基于1的2dim数组