Python的Zip函数的VBA版本(FOR EACH循环)

在Python中,我可以通过使用zip函数一次遍历多个列表。 我如何在Excel中的VBA的macros中做到这一点?

伪代码

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 

在VBA中没有直接的zip文件。
Note1将数据存入数组并在数组上循环而不是逐个单元地处理效率要高得多
Note2从单元格中获取.Text是非常不寻常的,因为它没有得到底层的值,可能会给####,而且速度慢:最好使用.Value2

如果范围是连续的,则最好使用二维数组,否则是四个单独的数组

 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 

如果你的实际代码在同一张表上的“列表”,相应的两三三在同一行,这可以为你工作。

 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