如何通过枚举值来声明(初始化)1-D和2-D固定大小的数组?

时间:2015-10-21 09:28:07

标签: excel vba excel-vba

我想在二维字符串数组中存储常量名称对。我可以写:

Dim a(2, 1) As String     '0 to 2, and 0 to 1
a(0, 0) = "one"
a(0, 1) = "first"
a(1, 0) = "two"
a(1, 1) = "second"
a(2, 0) = "three"
a(2, 1) = "third"

但是如果我通过查看即时给定的内容让VBA设置数组的大小,我认为它会更优雅,更可扩展。我想象这样的事情:

 Dim a({"one","first"}, _
       {"two","second"}, _
       {"three","third"}) as String

然后我意识到我甚至不知道如何通过即时枚举(初始化)声明一维阵列。

这有可能吗?如果是,怎么样?

那里有官方文件吗? (This不是。)

2 个答案:

答案 0 :(得分:2)

使其更优雅的最合理方法是创建基于给定字符串创建2D数组的新函数。

它可能如下所示:

Public Function create2DStringArray(ParamArray values() As Variant) As String()
    Dim varItem As Variant
    Dim strArray() As String
    Dim arraySize As Long
    Dim result() As String
    Dim iterator As Long
    '-------------------------------------------------------------------------------------------------

    On Error Resume Next
    arraySize = UBound(values) - LBound(values) + 1
    On Error GoTo 0


    ReDim result(0 To arraySize - 1, 0 To 1)


    For Each varItem In values
        strArray = VBA.Split(varItem, ";")
        result(iterator, 0) = strArray(0)
        result(iterator, 1) = strArray(1)
        iterator = iterator + 1
    Next varItem


    create2DStringArray = result


End Function

现在,您可以像这样初始化String数组:

Dim a() As String
a = create2DStringArray("one;first", "two;second", "three;third")

请注意,上述功能有一些限制:

  • 最多只能有30个参数,

  • 如果任何给定的字符串中包含分号,则它不起作用(除非您选择了另一个分隔符,我在上面使用了分号)。

答案 1 :(得分:1)

对于一维数组

Sub aArray()

Dim myarray As Variant

myarray = Array("One", "Two", "Three")


For i = 0 To UBound(myarray, 1)

Debug.Print myarray(i)

Next


End Sub