【问题标题】:Reading a CSV file with some empty values into an VBA array将带有一些空值的 CSV 文件读入 VBA 数组
【发布时间】:2019-04-02 07:03:39
【问题描述】:

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

数据文件 ¦ targetbook ¦ targetsheet ¦ firstrow ¦ 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”,因为拆分函数没有分裂任何东西。 如何处理空值?此外,我很高兴收到有关如何以更好的方式解决此任务的任何建议。

【问题讨论】:

  • one_line = Split(lines(0), ",") 将行 ",,,,,,,,,,,,,," 拆分为 15 个空字符串,您的数组 one_lineUbound 应该是 14。您确定发生错误的文本行包含这些逗号吗?
  • 我又检查了一遍,但确实只是一行逗号。如果我在“num_cols2 = UBound(one_line)”之后添加“Debug.Print num_cols2”,我得到的输出为 0
  • 这很奇怪。我经常使用 split-command 并且只是做了一个测试,我得到了 15 个元素。

标签: excel vba csv


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2023-03-27
    • 2013-12-11
    相关资源
    最近更新 更多