如何循环多个数组并使用 vba 显示值?

How to loop multiple arrays and display the values using vba?

如何循环多个数组并显示值?

示例数组:

结果:

当我这样做时效率不高,因为数组可能包含 1 个或多个值。我无法继续添加 list4、list5、list6 等等。

list1 = num(1) + ".... " + name(1) + ".... " + tag(1) + "<br/>"
list2 = num(2) + ".... " + name(2) + ".... " + tag(2) + "<br/>"
list3 = num(3) + ".... " + name(3) + ".... " + tag(3) + "<br/>"

Debug.Print list1 + list2 + list3

据我所知,无法动态创建变量名。我会为此使用多维数组,而不是 List3 = Num(3) 你会有 Lists(2,2)

'3 Lists with 3 entries per person but with 0 based array we declare it as 2,2
Dim Lists(2, 2) As String
'Declare counters for 2 For loops needed
Dim i As Long
Dim b As Long
'String to concatenate 3 entries for each person + formating
Dim Str As String
'Polulate array
Lists(0, 0) = 1
Lists(0, 1) = "Tesla"
Lists(0, 2) = "Tag 1"
Lists(1, 0) = 2
Lists(1, 1) = "John"
Lists(1, 2) = "Tag 2"
Lists(2, 0) = 3
Lists(2, 1) = "Mike"
Lists(2, 2) = "Tag 3"
'Loop through each person
For i = 0 To 2
    'Reset string at the begining of each loop
    Str = ""
    'Loop through each field for each person
    For b = 0 To 2
        'Add required dots as spacers if current field isn't the first one
        If b > 0 Then
            Str = Str + ".... "
        End If
        Str = Str + Lists(i, b)
    Next b
    'Once the fields are done add the <br/>
    Str = Str + "<br/>"
    'Do stuff with whole record before next iteration
    Debug.Print Str
Next i

... 或者,如果您得到数组,并且您知道它们的大小都相同,您可以

For i = 0 To UBound(num)
    Debug.Print CStr(num(i)) + ".... " + name(i) + ".... " + tag(i) + "<br/>"
Next i

选项 1(使用 Array())

Sub test1()
    Dim Num, Name, Tag, i
    Num = Array(1, 2, 3)
    Name = Array("Tesa", "John", "Mike")
    Tag = Array("tag1", "tag2", "tag3")
        
    For i = 0 To UBound(Num)
        Debug.Print Join(Array(Num(i), Name(i), Tag(i)), ".... ")
    Next
End Sub

选项 2(使用 Collection 和 Array())

Sub test2()
    Dim col As New Collection, i, a
    col.Add Array(1, 2, 3)
    col.Add Array("Tesa", "John", "Mike")
    col.Add Array("tag1", "tag2", "tag3")
    ' add any number of arrays into the collection
        
    ReDim a(1 To col.Count)
    For j = 0 To UBound(col(1))
        For i = 1 To col.Count: a(i) = col(i)(j): Next
        Debug.Print Join(a, ".... ")
    Next
End Sub

输出:

1.... Tesa.... tag1
2.... John.... tag2
3.... Mike.... tag3