很抱歉,我是一名自学成才的VBA程序员,我不知道如何表达我的问题!我已经声明了具有类似名称的常量,即
Public Const BP1Enable = "something1something:someotherthing1someotherthing"
public const BP2Enable = "something2something:someotherthing2someotherthing"
等等。
我有10个这样的常数。我有一个以这些常量为参数的子:
Sub FieldEnable (ByVal enableconst)
现在我想使用I作为计数器在循环中调用FieldEnable子:
For i = 1 To 10
BPfieldname = "BP" & i & "Enable"
FieldEnable enableconst:=BPfieldname
Next i
这不起作用,发生的情况是,在子字段Enable中分配给enableconst的"值"是"BP1Enable",而不是常数BP1Enabled的值,即"something1something:someotherthing1ssomeotherthing"。
调用子FieldEnable时,如何使用变量BPfieldname?
我希望这是有道理的。感谢您的帮助。
将变量转换为单个数组。
看看这个http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
编辑:正如@sina正确指出的,VBA不允许常量数组,
所以与其尝试这个
Dim BPEnable = {
"something1something:someotherthing1someotherthing",
"something2something:someotherthing2someotherthing",
....
}
你应该试试这个
Dim BPEnable
BPEnable = Array( _
"something1something:someotherthing1someotherthing", _
"something2something:someotherthing2someotherthing", _
"..."
)
For i = 0 To UBound(BPEnable)
BPfieldname = BPEnable(i)
Next i
最好使用常量数组,但VBA不支持常量数组。
因此,在开始循环之前,您可以用常量构建一个数组:
Dim BPEnable
BPEnable = Array(BP1Enable, BP2Enable)
For i = 0 To UBound(BPEnable)
FieldEnable enableconst:=BPEnable(i)
Next i
另一种选择是将所有常量声明为一个带有特定分隔符的长字符串,并在该字符串上使用split函数来生成数组。
此外,如果您要在多个地方、多个函数中使用这个"常量",您可以有效地使数组成为常量,甚至可以这样调用。
Public Sub Test()
For i = LBound(BPEnable) To UBound(BPEnable)
Debug.Print BPEnable(i)
Next i
End Sub
Public Function BPEnable() As Variant
BPEnable = Array("One", "Two", "Three", "Pi", "Four")
End Function
即时窗口:
One
Two
Three
Pi
Four