数组可以声明为常量吗?

问题描述 投票:15回答:8

有可能:

  1. 将数组声明为常量 要么
  2. 使用变通方法声明一个受保护的数组,以防止添加,删除或更改元素,因此在宏的生命周期中功能上保持不变?

我当然可以这样做:

Const myConstant1 As Integer = 2
Const myConstant2 As Integer = 13
Const myConstant3 As Integer = 17
Const myConstant4 ...and so on

...但它失去了使用数组的优雅。我还可以将常量加载到数组中,并在每次使用它们时重新加载它们,但是在使用之前无法使用这些常量值重新加载数组可能会将代码暴露给已更改的“常量”值。

任何可行的答案都是受欢迎的,但理想的答案是可以设置一次而不需要在修改其他代码时进行任何更改/维护。

arrays vba excel-vba constants excel
8个回答
26
投票

您可以使用函数返回数组并将该函数用作数组。

Function ContantArray()
    ContantArray = Array(2, 13, 17)
End Function

enter image description here

enter image description here


6
投票

如何使它成为一个功能?如:

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

没有人可以改变它,调整它或编辑它的内容......而且,你可以只在一行定义你的常量!


4
投票

我宣布了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 PreserveA时它没有让我。这种方法的缺点是你仍然可以编辑数组的值,即使你不能改变大小。


1
投票

如果特定的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

0
投票

数组可以声明为常量吗?没有。

变通方法 - 我能想到的最简单的方法是使用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

0
投票

否 - 数组不能声明为常量,但您可以使用变通方法。

您可以创建一个返回所需数组的函数

http://www.vbaexpress.com/forum/showthread.php?1233-Solved-Declare-a-Constant-Array


0
投票

如果每次都可以使用Static局部变量来避免多个对象创建和初始化时不需要新实例:

Private Function MyConstants()
    Static constants As Variant

    If IsEmpty(constants) Then
        constants = Array(2, 13, 17)
    End If

    MyConstants = constants
End Function

0
投票

这太简单了吗?

PUBLIC CONST MyArray = "1,2,3,4"

然后在一个模块中:

Dim Arr as Variant

SET Arr = split(MyArray,",")
© www.soinside.com 2019 - 2024. All rights reserved.