使用循环VBA将值分配给变量

时间:2016-12-08 15:24:33

标签: excel vba excel-vba

我在VBA函数中声明了变量,如A1,A2,A3 ..... An

并将值分配给A1,A2,A3 ...... An

现在如何使用循环

更新变量中的值
Dim A1, A2, A3 As Integer, Tmp As String
A1 = 1
A2 = 2
A3 = 3


For i = 1 To 3

    Debug.Print A & i
    A & i  = i+1 --- This line is not working
Next

如何在不使用任何数组的情况下分配变量

2 个答案:

答案 0 :(得分:2)

重新考虑使用数组:

Sub marine()
    Dim A(1 To 3) As Long
    A(1) = 1
    A(2) = 2
    A(3) = 3
End Sub

答案 1 :(得分:1)

您可以创建一个集合来执行此操作,然后循环集合或通过传入键(变量名称)来获取值

Sub TestCollection()
Dim i As Long
Dim objCollection As New Collection
Dim varVariable As Variant

    'Loop From 1 To 3. The Upper Bound Can Be Changed To Suit Your Needs
    For i = 1 To 3
        'Add The Key And Item To The Collection
        'The First Parameter Is The Item (Value You Want To Store)
        'The Second Parameter Is The Key (How You Access The Value, Like A Variable Name)
        objCollection.Add i, "A" & i
    Next i

    'The Value Passed Into The Collection Is The Key - Which Is Like The Variable Name
    Debug.Print objCollection("A1")
    Debug.Print objCollection("A2")
    Debug.Print objCollection("A3")

    'Loop All Values
    For Each varVariable In objCollection
        Debug.Print varVariable
    Next varVariable

End Sub