Arrays 在Visual Basic编辑器中声明全局数组

Arrays 在Visual Basic编辑器中声明全局数组,arrays,vba,Arrays,Vba,似乎没有其他答案适合我,所以我求助于问一个大家都认为有问题的问题。除了VBA以外的任何其他语言的简单内容。我只想初始化一个字符串的全局数组,并在我的main sub中使用它 这里是test1,我刚刚尝试从一个公共函数返回它: Public Function effthis1() As String() ReDim effthis1(0 To 10) myStr = "a b c d e f g h i j k" strsplit = Split(myStr) j

似乎没有其他答案适合我,所以我求助于问一个大家都认为有问题的问题。除了VBA以外的任何其他语言的简单内容。我只想初始化一个字符串的全局数组,并在我的main sub中使用它

这里是test1,我刚刚尝试从一个公共函数返回它:

Public Function effthis1() As String()
    ReDim effthis1(0 To 10)
    myStr = "a b c d e f g h i j k"
    strsplit = Split(myStr)

    j = LBound(effthis)
    For Each word In strsplit
        effthis1(j) = word
        j = j + 1
    Next

End Function

Sub test1()
    testStr = effthis1(4)
    MsgBox testStr
End Sub
这里是test2,我尝试使用一个在主sub中调用的sub:

Public effthis2() As String

Sub declareMyArray()

effthis2(0) = "a"
effthis2(1) = "b"
effthis2(2) = "c"
effthis2(3) = "d"
effthis2(4) = "e"
effthis2(5) = "f"
effthis2(6) = "g"
effthis2(7) = "h"
effthis2(8) = "i"
effthis2(9) = "j"
effthis2(10) = "k"

End Sub

Sub test2()
    declareMyArray
    MsgBox effthis2(4)
End Sub

MSDN毫无帮助。提前感谢George,在第二个示例中,您必须在分配数组之前分配数组的大小,因此将其更改为:

ReDim effthis2(10)

effthis2(0) = "a"
effthis2(1) = "b"
...

(公共数组也必须在模块中)

在第一个示例中,您必须声明变量,然后无需运行循环,只需获取该字符串即可

Public Function effthis1(j As Integer) As String
    Dim strsplit() As String
    myStr = "a b c d e f g h i j k"
    strsplit = Split(myStr)

    effthis1 = strsplit(j)

End Function

Sub test1()
    testStr = effthis1(4)
    MsgBox testStr
End Sub
编辑:

根据您的注释,teststr必须是一个数组,您可以在其中加载整个数组:

Public Function effthis1() As String()

    myStr = "a b c d e f g h i j k"
    effthis1 = Split(myStr)

End Function

Sub test1()

    teststr = effthis1
    MsgBox teststr(4)
End Sub

如果要在任何子模块或函数中使用变量,必须在顶部声明它,否则第一个子模块或函数会在子测试2()行上产生编译错误,说明子模块或函数未定义。我将示例2复制/粘贴到新模块中,添加
ReDim effthis2(10)
作为
declareMyArray
运行
test2
的第一行,它工作得很好。在我的示例代码中,我希望msgbox使用公共数组的第四个索引,而不是将其用作额外的输入参数。虽然,您的代码是一个方便的解决方法,我将记录并在将来使用。谢谢