循环变种

时间:2017-11-14 16:05:10

标签: vba excel-vba excel

我在VBA中声明这两个变量

Dim MyInteger As Integer
Dim MyVariant As Variant

我想将一个数字绑定到MyVariant,以便以下列方式将整数值以数字形式递增为变量:

MyVariant1 , MyVariant2, MyVariant3, MyVariant4, MyVariant5

我试图这样做,而不是以下列方式声明数百种变体:

MyVariant As Variant
MyVariant1 As Variant 
MyVariant2 As Variant 
MyVariant3 As Variant 
MyVariant4 As Variant 
MyVariant5 As Variant 

我正在尝试使用for循环执行此操作,但它似乎无法正常工作

Dim MyInteger As Integer
Dim MyVariant As Variant
For MyInteger = 1 To 5
MyVariant & MyInteger
Next MyInteger

1 个答案:

答案 0 :(得分:1)

只需将myVariant声明为变量变量数组。

Option Explicit

Sub Test()

    Dim myInteger As Integer, myVariants(1 To 255) As Variant

    For myInteger = 1 To 255
        myVariants(myInteger) = "SomeValue"
    Next myInteger

End Sub

如果您不确定所需的变量数量,可以这样做:

Option Explicit

Sub Test()

    Dim myInteger As Long, myVariants() As Variant
    Dim NumberNeeded As Long

    NumberNeeded = 'Some value
    ReDim myVariants(1 To NumberNeeded)

    For myInteger = 1 To UBound(myVariants)
        myVariants(myInteger) = "SomeValue"
    Next myInteger

End Sub