使用VBA将.csv字符串读入多维数组

时间:2017-07-18 21:27:33

标签: arrays excel vba csv

我正在尝试自动将数据导入到我在Excel中构建的工具中。我们的想法是将.csv文件中的数据直接读入数组,或者将数据作为字符串读取,然后使用空格“”和逗号“,”作为分隔符,后跟数组进行解析。我已经走到了这一步:

Public Sub ImportData()
    Dim myData as String, strData() as String
    Dim thisFile as String

    thisFile = ActiveWorkbook.Path & "\" & "s.csv"
    Open thisFile For Binary As #1
    myData = Space$(LOF(1))
    Get #1, , myData
    Close #1
End Sub

这让我看到“myData”是一个由逗号和空格分隔的现在数据字符串(逗号分隔新列,空格分隔新行)。

如何将其重建为多维(2D)数组,以便将其打印到我正在处理的工作表上,或直接从内存中引用?或者有更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

这是@Tim

建议的实现
Option Explicit

Public Sub OpenFile()
    Dim rawData As String, lineArr As Variant, cellArr As Variant
    Dim ubR As Long, ubC As Long, r As Long, c As Long

    Open ActiveWorkbook.Path & "\" & "s.csv" For Binary As #1
    rawData = Space$(LOF(1))
    Get #1, , rawData
    Close #1

    If Len(rawData) > 0 Then

        'If spaces are delimiters for lines change vbCrLf to " "
        lineArr = Split(Trim$(rawData), vbCrLf)

        ubR = UBound(lineArr) + 1
        ubC = UBound(Split(lineArr(0), ",")) + 1
        ReDim arr(1 To ubR, 1 To ubC)

        For r = 1 To ubR
            If Len(lineArr(r - 1)) > 0 Then
                cellArr = Split(lineArr(r - 1), ",")
                For c = 1 To ubC
                    arr(r, c) = cellArr(c - 1)
                Next
            End If
        Next
        ActiveSheet.Range(Cells(1), Cells(ubR, ubC)) = arr 'Place array on the sheet
    End If
End Sub