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
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With