有可能:
我当然可以这样做:
Const myConstant1 As Integer = 2
Const myConstant2 As Integer = 13
Const myConstant3 As Integer = 17
Const myConstant4 ...and so on
...但它失去了使用数组的优雅。我还可以将常量加载到数组中,并在每次使用它们时重新加载它们,但是在使用之前无法使用这些常量值重新加载数组可能会将代码暴露给已更改的“常量”值。
任何可行的答案都是受欢迎的,但理想的答案是可以设置一次而不需要在修改其他代码时进行任何更改/维护。
如何使它成为一个功能?如:
Public Function myConstant(ByVal idx As Integer) As Integer
myConstant = Array(2, 13, 17, 23)(idx - 1)
End Function
Sub Test()
Debug.Print myConstant(1)
Debug.Print myConstant(2)
Debug.Print myConstant(3)
Debug.Print myConstant(4)
End Sub
没有人可以改变它,调整它或编辑它的内容......而且,你可以只在一行定义你的常量!
我宣布了String
的"1,2,3,4,5"
常量,然后使用Split
创建一个新数组,如下所示:
Public Const myArray = "1,2,3,4,5"
Public Sub createArray()
Dim i As Integer
A = Split(myArray, ",")
For i = LBound(A) To UBound(A)
Debug.Print A(i)
Next i
End Sub
当我试图在ReDim
上使用ReDim Preserve
或A
时它没有让我。这种方法的缺点是你仍然可以编辑数组的值,即使你不能改变大小。
如果特定的VBA环境是Excel-VBA,则可以从Excel应用程序的Evaluate方法获得一个很好的语法,该方法可以缩短为方括号。
看这个
Sub XlSerialization1()
Dim v
v = [{1,2;"foo",4.5}]
Debug.Assert v(1, 1) = 1
Debug.Assert v(1, 2) = 2
Debug.Assert v(2, 1) = "foo"
Debug.Assert v(2, 2) = 4.5
'* write all cells in one line
Sheet1.Cells(1, 1).Resize(2, 2).Value2 = v
End Sub
数组可以声明为常量吗?没有。
变通方法 - 我能想到的最简单的方法是使用delim定义一个常量,然后使用Split
函数创建一个数组。
Const myConstant = "2,13,17"
Sub Test()
i = Split(myConstant, ",")
For j = LBound(i) To UBound(i)
Debug.Print i(j)
Next
End Sub
否 - 数组不能声明为常量,但您可以使用变通方法。
您可以创建一个返回所需数组的函数
http://www.vbaexpress.com/forum/showthread.php?1233-Solved-Declare-a-Constant-Array
如果每次都可以使用Static
局部变量来避免多个对象创建和初始化时不需要新实例:
Private Function MyConstants()
Static constants As Variant
If IsEmpty(constants) Then
constants = Array(2, 13, 17)
End If
MyConstants = constants
End Function
这太简单了吗?
PUBLIC CONST MyArray = "1,2,3,4"
然后在一个模块中:
Dim Arr as Variant
SET Arr = split(MyArray,",")