将具有一些空值的CSV文件读取到VBA数组中

时间:2019-04-02 07:03:39

标签: excel vba csv

由于我们在许多软件文档中都使用Excel,所以我认为拥有版本控制会很好,尤其是考虑到它已经使用旧版本多次了。 我想要做的是拥有一个包含所有工作表,索引和格式以及分离的csv文件中的数据的骨架Excel文件。另外,在config.csv中,我想定义以下内容:

数据文件¦ targetbook target targetsheet ¦ firstrow first firstcolumn

我第一次使用VBA,因此我基本上只是一起复制粘贴代码,但这是我到目前为止所得到的:

folderpath = Application.ActiveWorkbook.Path
configpath = (folderpath & "\config.csv")

' Load the file.
fnum = FreeFile
Open configpath For Input As fnum
whole_file = Input$(LOF(fnum), #fnum)
Close fnum

' Break the file into lines.
lines = Split(whole_file, vbCrLf)

' Dimension the array.
num_rows = UBound(lines)
one_line = Split(lines(0), ",")
num_cols = UBound(one_line)
ReDim the_array(num_rows, num_cols)

' Copy the data into the array.
For R = 0 To num_rows
    If Len(lines(R)) > 0 Then
        one_line = Split(lines(R), ",")
        For C = 0 To num_cols
            the_array(R, C) = one_line(C)
        Next C
    End If
Next R

' Process first line of config file

For R = 1 To num_rows

    datafilepath = (folderpath & "\" & the_array(R, 0) & ".csv")

    ' Load the file.
    fnum = FreeFile
    Open datafilepath For Input As fnum
    whole_file = Input$(LOF(fnum), #fnum)
    Close fnum

    ' Break the file into lines.
    lines = Split(whole_file, vbCrLf)

    ' Dimension the array.
    num_rows2 = UBound(lines)
    one_line = Split(lines(0), ",")
    num_cols2 = UBound(one_line)
    ReDim the_array2(num_rows2, num_cols2)

    ' Copy the data into the array.
    For R2 = 0 To num_rows2
        If Len(lines(R2)) > 0 Then
            one_line = Split(lines(R2), ",")
            For C2 = 0 To num_cols2
                the_array(R2, C2) = one_line(C2)
            Next C2
        End If
    Next R2
Next R    

我收到以下错误“运行时错误'9':下标超出范围”,我认为这是因为csv数据文件包含空值。因此,例如,如果我有一个完全空的行,例如“ 、、、、、、、、、、、、” num_cols2 = UBound(one_line)将num_cols2的值设置为“ 0”,因为Split函数没有分割任何东西。 如何处理空值?另外,对于如何以更好的方式解决此任务的任何建议,我都会感到高兴。

1 个答案:

答案 0 :(得分:0)

您可以打开文件并在“文本到列” csv中打开吗?如果可以,那么您可以轻松地作为一个简单的表来工作。