在Python中,我可以使用zip函数一次遍历多个列表。我如何在Excel中的VBA宏中执行此操作?
伪代码
Set ones = Worksheets("Insertion").Range("D2:D673")
Set twos = Worksheets("Insertion").Range("A2:A673")
Set threes = Worksheets("Insertion").Range("B2:B673")
Set fours = Worksheets("Insertion").Range("C2:C673")
For Each one, two, three, four in zip(ones.Cells, twos.Cells, threes.Cells, fours.Cells)
Debug.Print(one.Text & two.Text & three.Text & four.Text)
Next one
答案 0 :(得分:3)
VBA中没有拉链的直接等效词 注1,将数据放入数组并在数组上循环更有效,而不是逐个单元地处理 注2:从单元格中获取.Text是非常不寻常的,因为它没有得到基础值,可能会给####,而且速度慢:更好用.Value2
如果范围是连续的,最好使用2D数组,否则使用4个单独的数组
Sub testing1()
Dim var As Variant
Dim j As Long
Dim k As Long
Dim str As String
var = Worksheets("Sheet1").Range("A2:D673").Value2
For j = LBound(var) To UBound(var)
For k = LBound(var, 2) To UBound(var, 2)
str = str & var(j, k) & " "
Next k
Debug.Print str
str = ""
Next j
End Sub
Sub testing2()
Dim varA As Variant
Dim varB As Variant
Dim varC As Variant
Dim varD As Variant
Dim j As Long
varA = Worksheets("Sheet1").Range("A2:A673").Value2
varB = Worksheets("Sheet1").Range("B2:B673").Value2
varC = Worksheets("Sheet1").Range("C2:C673").Value2
varD = Worksheets("Sheet1").Range("D2:D673").Value2
For j = LBound(varA) To UBound(varA)
Debug.Print varA(j, 1) & " " & varB(j, 1) & " " & varC(j, 1) & " " & varD(j, 1)
Next j
End Sub
答案 1 :(得分:0)
如果您的实际代码在同一张纸上有“列表”,而相应的那些 - 两个 - 三 - 四 - 在同一行,这可能适合您。
Dim ws As Worksheet
Set ws = ActiveSheet
Set rng = ws.Range("A2:D673")
For Each rw In rng.Rows
' where 4 is the column number of the D-column
ones = ws.Cells(rw.Row, 4).Value
twos = ws.Cells(rw.Row, 1).Value
threes = ws.Cells(rw.Row, 2).Value
fours = ws.Cells(rw.Row, 3).Value
Next rw