我可以使用For循环定义和填充变量吗?

时间:2019-07-01 12:59:19

标签: excel vba

如何填充一系列使用通用前缀后跟数字的变量(使用For循环),这样我就不必单独编写它们了?

我之前看过它,但是我找不到要复制的示例。有点类似...

For i = 0 to 9
    var("Home" & i) = "Yes"
Next i

TIA

3 个答案:

答案 0 :(得分:3)

每当您认为“变量变量名称”而不是“数组”时。

Dim HomeArray(0 to 9) As String

For i = 0 to 9
    HomeArray(i) = "Yes"
Next i

答案 1 :(得分:1)

这是可能的,但前提是您的变量是PUBLIC且在CLASS中:

' Class1

Public Home0 As String
Public Home1 As String
Public Home2 As String
Public Home3 As String
Public Home4 As String
Public Home5 As String
Public Home6 As String
Public Home7 As String
Public Home8 As String
Public Home9 As String

然后您可以像这样使用CallByName()

' Module1

Dim C1 As New Class1

Sub Foo_In_Module1()
    Debug.Print "Before: Home0 = " & C1.Home0
    For i = 0 To 9
        CallByName C1, "Home" & i, VbLet, "Yes"
    Next i
    Debug.Print "After: Home0 = " & C1.Home0
End Sub

在我的即时窗口中输出:

enter image description here

使用CallByName()检索相同值的示例:

Sub Foo2_In_Module1()
    Dim varName As String
    For i = 0 To 9
        varName = "Home" & i
        Debug.Print varName & " = " & CallByName(C1, varName, VbGet)
    Next i
End Sub

答案 2 :(得分:0)

也许您正在寻找的是字典:

dict.Add Key:="Orange", Item:=45

如果要设置“ orange”的值,可以这样使用:

dict("Orange") = 75

看看Here