简体   繁体   English

VBA-公共阵列错误-下标超出范围

[英]VBA - Public Array Error - Subscript out of range

I want to declare a public array, create it and then use it in another sub. 我想声明一个公共数组,创建它,然后在另一个子目录中使用它。 This is exapmle of what I wrote: 这是我写的例子:

Public array1() As String

Sub Create_Array()

Dim array1(1 To 4) As String

array1(1) = "1"
array1(2) = "2"
array1(3) = "A"
array1(4) = "B"

End Sub

Sub Show_Some_Index()

Dim a As String
a = array1(1)
MsgBox (a)

End Sub

I get Error 9: "Subscript out of range". 我收到错误9:“下标超出范围”。 Couldn't find an answer, what am I doing wrong? 找不到答案,我在做什么错?

Variable array1() in Sub Create_Array is scoped to that procedure - basically it's a local variable that's only ever accessible within that procedure, and it happens to have the same name as another public field declared elsewhere, so what's happening is that Show_Some_Index is working off an array that hasn't been initialized yet. Sub Create_Array变量array1() Sub Create_Array该过程-基本上,这是一个只能在该过程中访问的局部变量,并且它的名称与在其他地方声明的另一个公共字段的名称相同,所以发生的是Show_Some_Index正在起作用一个尚未初始化的数组。

Dim is used for declaring variables. Dim用于声明变量。 If you mean to re-dimension an array that's in-scope, use the ReDim keyword. 如果要重新定义范围内的数组,请使用ReDim关键字。


A better approach would be to use a function that returns the array, instead of relying on global variables. 更好的方法是使用返回数组的函数,而不是依赖于全局变量。

I want to declare a public array, create it and then use it in another sub. 我想声明一个公共数组,创建它,然后在另一个子目录中使用它。

In that case remove the Dim Statement from your code. 在这种情况下,请从代码中删除Dim语句。 Further to what Mat explained, here is another way to make your code work 根据Mat的解释,这是使代码正常工作的另一种方法

WAY 1 方式1

Public array1(1 To 4) As String

Sub Create_Array()
    array1(1) = "1"
    array1(2) = "2"
    array1(3) = "A"
    array1(4) = "B"

    Show_Some_Index
End Sub

Sub Show_Some_Index()
    Dim a As String
    a = array1(1)
    MsgBox (a)
End Sub

WAY 2 方式2

Public array1(1 To 4) As String

Sub Create_Array()
    array1(1) = "1"
    array1(2) = "2"
    array1(3) = "A"
    array1(4) = "B"
End Sub

Sub Show_Some_Index()
    Create_Array

    Dim a As String
    a = array1(1)
    MsgBox (a)
End Sub

Once you initialize it, you should be able to use it in other procedures. 初始化后,应该可以在其他过程中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM