【问题标题】:declaring global array in Visual Basic Editor在 Visual Basic 编辑器中声明全局数组
【发布时间】:2015-10-05 23:55:09
【问题描述】:

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

这是我刚刚尝试从公共函数返回的 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,我尝试使用在主子中调用的子:

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 根本没有帮助。在此先感谢,乔治

【问题讨论】:

  • 如果你想在任何子或函数中使用变量,你必须在顶部声明它,在第一个子或函数之前

标签: arrays vba


【解决方案1】:

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

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

【讨论】:

  • 在我的示例代码中,我打算让 msgbox 使用公共数组的第 4 个索引,而不是将其用作附加输入参数。虽然,您的代码是一个方便的解决方法,但我将在未来记录和使用。谢谢!
【解决方案2】:

在第二个示例中,您必须先分配数组的大小,然后再分配给它,因此将其更改为:

ReDim effthis2(10)

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

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

【讨论】:

  • 在子 test2() 行产生编译错误,说明子或函数未定义。
  • 我将示例 2 复制/粘贴到一个新模块中,添加 ReDim effthis2(10) 作为 declareMyArray 的第一行运行 test2 并且它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多