2

No other answer seems to work for me so I'm resorting to asking a question that everyone sees to be having trouble with. Simple stuff on any other language but VBA. I just want to initialize a global array of strings, and make use of it in my main sub.

Here's test1 where I just tried to return it from a public function:

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

Here's test2 where I tried with a sub that gets called within the main 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 is not helping at all. Thanks in advance, George

1
  • if you want to use a variable in any sub or function you have to declare it at the top, before the first sub or function Commented Oct 5, 2015 at 15:23

2 Answers 2

2

With your first example, You must declare the variable, then ther is no need to run a loop just get that string.

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

Edit:

Per your comment then the teststr must be an array into which you load the entire array:

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
Sign up to request clarification or add additional context in comments.

1 Comment

With my example code, I intend the msgbox to use the 4th index of the public array, not use it as an additional input argument. Although, your code is a handy workaround for that, that I'll record and use in the future. Thanks!
1

In the 2nd example you must allocate the size of the array prior to assigning to it, so change it to:

ReDim effthis2(10)

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

(A public array must also be within a module)

2 Comments

Yields a compile error on the sub test2() line, stating the sub or function is not defined.
I copy/paste example 2 into a new module, add ReDim effthis2(10) as the first line of declareMyArray run test2 and it works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.