PDA

View Full Version : Solved: Returning an array of strings with a function



gmaxey
07-19-2010, 08:01 PM
The little voice is telling me that I should know better than to ask, but I am going to ask anyway.

The sampling of code below shows how I could use a function to get the string data type elements for a small array.


Sub Test()
Dim myArr() As String
ReDim myArr(1, 1)
myArr = getMyArrData
MsgBox myArr(0, 0)
End Sub

Function getMyArrData() As Variant
Dim tempArr(1, 1) As String
tempArr(0, 0) = "Test 1"
tempArr(1, 0) = "Test 2"
tempArr(0, 1) = "Test 3"
tempArr(1, 1) = "Test 4"
getMyArrData = tempArr
End Function


It seems I stuck with using the "Variant" datatype for the function. What I am wondering is if there is not a more direct approach? I was thinking something like:

Function getMyArrData(1, 1) as String
getMyArrData(0, 0) = "Test 1"
getMyArrData(1, 0) = "Test 2"
...
...
End Function

... would work, but it certainly doesn't.

Thanks.

fumei
07-21-2010, 09:40 AM
Hi Greg.

Function getMyArrData(1, 1) as String

... would work, but it certainly doesn't.

No, it certainly does not. VBA is looking at getMyArrData(1,1) with the (1,1) as parameters, and as such they have to be defined data types...not values.

It is possible to use a string arrays, rather than Variant, but is this a real issue?
Option Explicit
Public myArr() As String
Sub Test()
ReDim myArr(1, 1)
Call getMyArrData(0, 1)
MsgBox myArr(0, 0)
End Sub
Function getMyArrData(Num1 As Long, Num2 As Long) As String
Dim tempArr(1, 1) As String
tempArr(Num1, Num1) = "Test 1"
tempArr(Num2, Num1) = "Test 2"
tempArr(Num1, Num2) = "Test 3"
tempArr(Num2, Num2) = "Test 4"
myArr() = tempArr()
End Function

fumei
07-21-2010, 09:43 AM
You could also do it a Sub, rather than a Function if you do not need to use variables for the array dimensions.
Option Explicit
Public myArr() As String
Sub Test()
ReDim myArr(1, 1)
Call getMyArrData
MsgBox myArr(0, 0)
End Sub

Sub getMyArrData()
Dim tempArr(1, 1) As String
tempArr(0, 0) = "Test 1"
tempArr(1, 0) = "Test 2"
tempArr(0, 1) = "Test 3"
tempArr(1, 1) = "Test 4"
myArr() = tempArr()
End Sub

gmaxey
07-21-2010, 03:57 PM
Gerry,

Thanks. No it isn't really an issue. I know that my array data members are strings and I was just looking for a way to simplify some code using a function and couldn't understand why I seeme stuck using a Variant.

fumei
07-22-2010, 10:22 AM
Chuckle... 'cause that is the way it is. In some ways, it does sort of make sense.