使用VBA动态设置变量值

时间:2019-07-29 08:39:54

标签: excel vba

我不太使用VBA,直到DFromRow1为止,我都有许多全局整数变量,例如DFromRow2DFromRow3DFromRow20。我想以此方式依次设置每个(这只是一个非常简单的示例,可以帮助您了解我要执行的操作):

Dim Count as integer
Count = 0
Begin Loop(loop here for 20 times)

    Count = Count + 1

    DFromRow & Count = Count

End Loop

这里的想法是全局变量将这样填充:

DFromRow1 = 1
DFromRow2 = 2
DFromRow3 = 3
... up until 20

但是我在&上出现错误:

  

预期:表达式

有没有办法做到这一点,或者我对自己想要的东西太过雄心勃勃?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以使用数组而不是声明20个变量DFromRow
这样的东西

Option Explicit

Public ArrDFromRow(20)

Sub Test()

    Dim i As Long

    For i = 1 To 20
        ArrDFromRow(i) = i
    Next i

    For i = 1 To 20
        Debug.Print ArrDFromRow(i)
    Next i

End Sub

答案 1 :(得分:0)

您可以使用Array这样存储值:

Dim DRowArray(1 to 20) as Long

Sub PopulateDFromRowArray()
    Dim i as Integer
    For i = LBound(DRowArray) to UBound(DRowArray)
        DRowArray(i) = i
    Next
End Sub

还是字典,尽管您需要将VBA引用设置为Microsoft Scripting Runtime

Dim DRowDict as Scripting.Dictionary

Sub PopulateDFromRowDictionary()
    Dim i as Integer
    Set DRowDict = New Scripting.Dictionary
    For i = 1 To 20
        DRowDict.Add "DFromRow" & i, i
    Next
End Sub