Jennifer
08-22-2013, 08:27 PM
I would like to write a some VBA code for use in a Word macro that needs to generate a list of values according to another list.
The source list is of the form value, count, value, count, ... For example: "red", 5, "blue", 3, "green", 2.
The result list will have 10 entries: 5 "red"'s, 3 "blues"'s, and 2 "greens"'s: "red", "red", "red", "red", "red", "blue", "blue", "blue", "green", "green". I don't care about the order.
The calling syntax would be something like this:
result = GenArray("Red", 5, "Blue", 3, "Green", 1, ...)
I came up with a solution that returns a delimited string, which the caller then needs to Split into an Array:
...caller code
Dim ColorSet As String
Dim ColorArray() As String
ColorSet = GenArray("Red", 5, "Blue", 3, "Green", 1)
ColorArray = Split(ColorSet, " ")
... caller code
Here's the Function code:
Function GenArray(ParamArray Param() As Variant)
Dim i1 As Integer 'Loop index
Dim i2 As Integer 'Color array index
For i1 = 0 To UBound(Param) Step 2
'Call MsgBox("Parm " & i & " = " & Param(i), vbOK, "GenArray")
For i2 = 1 To Param(i1 + 1)
GenArray = GenArray & " " & Param(i1)
Next i2
Next i1
End Function
This works. Two questions:
Is there a better way?
Is there a way for the function to so the Split and return the array?
Thanks
The source list is of the form value, count, value, count, ... For example: "red", 5, "blue", 3, "green", 2.
The result list will have 10 entries: 5 "red"'s, 3 "blues"'s, and 2 "greens"'s: "red", "red", "red", "red", "red", "blue", "blue", "blue", "green", "green". I don't care about the order.
The calling syntax would be something like this:
result = GenArray("Red", 5, "Blue", 3, "Green", 1, ...)
I came up with a solution that returns a delimited string, which the caller then needs to Split into an Array:
...caller code
Dim ColorSet As String
Dim ColorArray() As String
ColorSet = GenArray("Red", 5, "Blue", 3, "Green", 1)
ColorArray = Split(ColorSet, " ")
... caller code
Here's the Function code:
Function GenArray(ParamArray Param() As Variant)
Dim i1 As Integer 'Loop index
Dim i2 As Integer 'Color array index
For i1 = 0 To UBound(Param) Step 2
'Call MsgBox("Parm " & i & " = " & Param(i), vbOK, "GenArray")
For i2 = 1 To Param(i1 + 1)
GenArray = GenArray & " " & Param(i1)
Next i2
Next i1
End Function
This works. Two questions:
Is there a better way?
Is there a way for the function to so the Split and return the array?
Thanks