Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Public Array : how to?

Tags:

arrays

vba

So today's problem is getting me mad because that should be easy and i can not find the answer :

How to declare a public array in VBA ? I'm using an array with the letters A, B, C,... because i'm working with Excel cells, and i don't want to declare it in every function i create, right ? I've tried to look on the web first and i read that you have to declare it in a different module, so that's what i've done :

Public colHeader As String
colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

But Visual Basic doesn't like it...

So what shall i do ?

Thank's a lot :)

Edit : the problem is more about asigning values to the array than to declare it

like image 961
Julien Avatar asked Oct 31 '09 12:10

Julien


3 Answers

Option Explicit

Public colHeader

Sub test()

    ReDim colHeader(11)
    colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Sub

Sub verify_test()

    Dim i As Integer
    For i = LBound(colHeader) To UBound(colHeader)
        MsgBox "colHeader( " & i & " ) = " & colHeader(i)
    Next
End Sub
like image 195
sskerui Avatar answered Oct 19 '22 10:10

sskerui


You are using the wrong type. The Array(...) function returns a Variant, not a String.

Thus, in the Declaration section of your module (it does not need to be a different module!), you define

Public colHeader As Variant

and somewhere at the beginning of your program code (for example, in the Workbook_Open event) you initialize it with

colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Another (simple) alternative would be to create a function that returns the array, e.g. something like

Public Function GetHeaders() As Variant
    GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function

This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.

like image 9
Heinzi Avatar answered Oct 19 '22 10:10

Heinzi


Declare array as global across subs in a application:

Public GlobalArray(10) as String
GlobalArray = Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')

Sub DisplayArray()
    Dim i As Integer

    For i = 0 to UBound(GlobalArray, 1)
        MsgBox GlobalArray(i)

    Next i
End Sub

Method 2: Pass an array to sub. Use ParamArray.

Sub DisplayArray(Name As String, ParamArray Arr() As Variant)
    Dim i As Integer

    For i = 0 To UBound(Arr())
        MsgBox Name & ": " & Arr(i)
    Next i
End Sub

ParamArray must be the last parameter.

like image 8
Stanislav Stoyanov Avatar answered Oct 19 '22 09:10

Stanislav Stoyanov