Populate a variant array from a comma-delimited string

Aiken picture Aiken · Apr 10, 2015 · Viewed 17.4k times · Source

Usually if I want to create an array from a comma-delimited string then it's a String array I want and the Split() function I'll use. However right now I need to convert a comma-delimited string into a Variant array so it can be used as a function argument.

Unfortunately attempting to populate a variant array using Split() is throwing a Type Mismatch error, test example below.

Public Sub GetTheStuff()
    Dim varArray() As Variant

    varArray = Split("Bob,Alice,Joe,Jane", ",") '<~~ Error 13, Type Mismatch

    DoTheThing varArray
End Sub

Private Sub DoTheThing(Args() As Variant)
    Dim i As Long

    For i = LBound(Args) To UBound(Args)
        Debug.Print Args(i)
    Next i
End Sub

Is there a simple way to populate a Variant array from a delimited string, or am I going to have to write my own function to do so?

Note: I can't change the fact that the function I'm calling requires a Variant array as an argument, nor can I get my input as anything other than a delimited string.

Answer

Comintern picture Comintern · Apr 10, 2015

In a word, no - there isn't a Split function that will return an array of Variant. You basically have 2 options - if the array is small(ish), you can convert it:

Dim rawArray() As String
Dim varArray() As Variant

rawArray = Split("Bob,Alice,Joe,Jane", ",")
ReDim varArray(LBound(rawArray) To UBound(rawArray))

Dim index As Long
For index = LBound(rawArray) To UBound(rawArray)
    varArray(index) = rawArray(index)
Next index

The second option you already mentioned in the question - write your own CSV parser (annoying but also not horribly difficult).