2

例如,如果我有数组:

DeviceArray = Array("Sw","Cap","Gen","Reg","Tr","Br")

我想将所有内容初始化为一个值,例如 0,这相当于为此编写一个 for 循环,以便将数组中的值视为变量名,以便我可以间接修改变量值:

For i = 0 to ubound(DeviceArray)
     DeviceArray(i) = 0
Next i

这样在运行代码后,变量:Sw、Cap、Gen、Reg、Tr 和 Br 都应设置为 0。

与将 DeviceArray 中的每个元素更改为 0 并且不再存储最初放置的字符串相比。

所以 DeviceArray 应该保持不变并且仍然存储值("Sw","Cap","Gen","Reg","Tr","Br")

希望清楚地解释我想要做什么,我正在尝试这样做,所以我不必输入:

Sw = 0
Cap = 0
Gen = 0
Reg = 0
Tr = 0
Br = 0

因为在我的宏中有一长串变量需要不断地重新初始化为不同的值。

例如DeviceArray(0) = Sw,但我希望 VBA 宏将其识别DeviceArray(0)为变量的名称,Sw这样我就可以修改变量的值Sw而无需直接调用它。

4

1 回答 1

4

听起来您正在寻找引用类型而不是值类型。为此,您将需要 VBA 中的对象。

例如,创建一个名为Device. 在最简单的情况下,您可以将其Public value作为类中的唯一代码。

'Class Device
Public value

现在您可以按名称引用对象并传递这些引用,例如将它们放入Array您的示例中。

'Within a normal module

Public Sub test()
    Dim Sw As New Device
    Dim Cap As New Device
    Dim Gen As New Device
    Dim Reg As New Device
    Dim Tr As New Device
    Dim Br As New Device

    DeviceArray = Array(Sw, Cap, Gen, Reg, Tr, Br)
    For i = LBound(DeviceArray) To UBound(DeviceArray)
       DeviceArray(i).value = 42
    Next i

    Debug.Print Gen.value
End Sub

'Output is 42

或者,根据您的需要,哈希映射也可以解决问题,在这种情况下,您不会声明变量,而是在映射中引用它们的条目。

Public Sub test2()
    Dim Devices As Object, DeviceArray
    Set Devices = CreateObject("Scripting.Dictionary")
    DeviceArray = Array("Sw", "Cap", "Gen", "Reg", "Tr", "Br")

    For i = 0 To UBound(DeviceArray)
        Devices(DeviceArray(i)) = 0
    Next i

    Debug.Print "Gen init to ", Devices("Gen")

    Devices("Gen") = 42

    Debug.Print "Gen is now ", Devices("Gen")

    For i = 0 To UBound(DeviceArray)
        Devices(DeviceArray(i)) = 0
    Next i

    Debug.Print "Gen reset to ", Devices("Gen")
End Sub


'Gen init to    0 
'Gen is now     42 
'Gen reset to   0 
于 2013-07-03T18:49:37.383 回答