从逗号分隔的字符串填充变量数组

时间:2015-04-10 09:00:08

标签: vba ms-access-2003

通常如果我想用逗号分隔的字符串创建一个数组,那么它就是我想要的String数组和我将使用的Split()函数。但是现在我需要将逗号分隔的字符串转换为Variant数组,以便它可以用作函数参数。

不幸的是,尝试使用Split()填充变体数组会引发类型不匹配错误,下面是测试示例。

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

是否有一种简单的方法可以从分隔的字符串填充Variant数组,或者我是否必须编写自己的函数来执行此操作?

注意:我无法改变我正在调用的函数需要Variant数组作为参数的事实,也不能将我的输入作为除分隔字符串之外的任何内容。

2 个答案:

答案 0 :(得分:2)

总之,没有 - 没有Split函数会返回Variant数组。你基本上有2个选项 - 如果数组很小(ish),你可以转换它:

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

你在问题​​中已经提到的第二个选项 - 编写自己的CSV解析器(烦人但也不是非常困难)。

答案 1 :(得分:1)

将CSV数据导入二维变体数组中 数字作为值, 日期为日期, string as string。

' Import CSV data into two dimensional variant array with numeric as value, date as date, string as string.
Private Function CSV_to_Array(CSV As String)

 Dim CSV_Rows() As String

 CSV_Rows() = Split(CSV, Chr(10)) ' split the CSV into rows

 ' Import CSV data into two dimensional variant array with numeric as value, date as date, string as string.
 aryWidth = 0
 ReDim Ary(0 To UBound(CSV_Rows), 0 To aryWidth) As Variant

 For Y = LBound(CSV_Rows) To UBound(CSV_Rows)

    CSV_Fields = Split(CSV_Rows(Y), ",")

    If UBound(CSV_Fields) > aryWidth Then
        aryWidth = UBound(CSV_Fields)
        ReDim Preserve Ary(0 To UBound(CSV_Rows), 0 To aryWidth) As Variant
    End If

    For X = LBound(CSV_Fields) To UBound(CSV_Fields)
        If IsNumeric(CSV_Fields(X)) Then
            Ary(Y, X) = Val(CSV_Fields(X))
        ElseIf IsDate(CSV_Fields(X)) Then
            Ary(Y, X) = CDate(CSV_Fields(X))
        Else
            Ary(Y, X) = CStr(CSV_Fields(X))
        End If
    Next

 Next

 CSV_to_Array = Ary()

End Function


Dim Ary() As Variant
Ary() = CSV_to_Array(strCSV)