简体   繁体   中英

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". 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.

Dim is used for declaring variables. If you mean to re-dimension an array that's in-scope, use the ReDim keyword.


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. Further to what Mat explained, here is another way to make your code work

WAY 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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