将包含一些空值的CSV文件读入VBA数组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将包含一些空值的CSV文件读入VBA数组相关的知识,希望对你有一定的参考价值。
由于我们在许多软件文档中使用Excel,因此我认为对版本控制会很好,特别是考虑到已经多次使用旧版本。我想要做的是拥有一个骨架Excel文件,其中包含所有工作表,索引和格式以及separat csv文件中的数据。另外在config.csv中我想定义以下内容:
datafile | 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”,因为Split函数没有拆分任何东西我该如何处理空值?此外,我很高兴有关如何以更好的方式解决此任务的任何建议。
答案
你可以打开文件和“文本到列”csv?如果可以,那么你可以轻松地作为一个简单的表工作。
以上是关于将包含一些空值的CSV文件读入VBA数组的主要内容,如果未能解决你的问题,请参考以下文章
用python.检查“影片名称”字段为空值的+数据,给该字段填充数+据"unnamed"?