All,
I would like to write a function to return an array of integers so I can index them, but I am not aware of the syntax for VBA. Here is the pseudo code:
Function getStats() As Variant
getStats is now an Array and not an Integer
I'm going to add an answer here because I'm happy to say, after hours of frustration and bad information, I finally know how to return arrays! Here is how you return an array from a function:
Sub mysub()
Dim i As Integer, s As String
Dim myArray() As Integer 'if you declare a size here you will get "Compile error, can't assign to array"
myArray = getStats()
s = "Array values returned:" & vbCrLf
For i = 0 To UBound(myArray)
s = (s & myArray(i) & " ")
Next
MsgBox s
End Sub
Function getStats() As Integer() 'The return type must be EXACTLY the same as the type declared in the calling sub.
Dim returnVal(2) As Integer 'if you DON'T declare a size here you will get "Run-time error '9': Subscript out of range"
returnVal(0) = 0
returnVal(1) = 1
returnVal(2) = 2
'returnVal(3) = 3 This will throw an error. Remember that an array declared (2) will hold 3 values, 0-2.
getStats = returnVal
End Function
Output:
The comments I included here are very important. Although VBA is usually pretty lax, this particular thing is very picky. These are required for your function, assignment, and return to work:
Give the function the type as an array:
function getStats() as Integer()
dim returnVal(0 to 3) as integer
returnVal(0) = c2percent14
returnVal(1) = c3percent14
returnVal(2) = c4percent14
returnVal(3) = c5percent14
getStats = returnVal
end function
Sub mysub()
Dim myArray() As Integer
myArray = getStats()
msgbox myArray(3)
end sub