简而言之,我将CSV文件导入Excel工作表,并且希望能够区分CSV中没有数据的单元格和不是#&的单元格。 39; t在CSV中。
例如,让以下文件在文件" test.csv"
1,2,3,4
5,,7,
9,10
13,14,15,16
然后,在VBA宏中,我将此文件作为查询表加载(代码主要从http://www.zerrtech.com/content/excel-vba-open-csv-file-and-import复制):
With Sheet1.QueryTables.Add(Connection:="TEXT;test.csv", _
Destination:=Sheet1.Range("A1"))
.Name = "Table1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.Refresh BackgroundQuery:=False
End With
将CSV加载到单元格中,如下所示:
| A | B | C | D |
---+-----+-----+-----+-----+
1 | 1 | 2 | 3 | 4 |
---+-----+-----+-----+-----+
2 | 5 | | 7 | |
---+-----+-----+-----+-----+
3 | 9 | 10 | | |
---+-----+-----+-----+-----+
4 | 13 | 14 | 15 | 16 |
---+-----+-----+-----+-----+
所以,我的问题是如何区分空单元格B2和D2(在CSV中被定义为空)与空单元格C3和D3(它们未在CSV)?如果没有办法从加载的查询表中执行此操作,是否有一种不同的导入CSV的方法可以适应这种情况?
答案 0 :(得分:1)
可能有更简单的方法来确定每行中的总导入值,但目前:
Option Explicit
Public Sub csvCounter()
Const FILE_NAME As String = "C:\empty.csv"
Const DELIM As String = ","
Dim fso As Object, txt As Object, dat As String, i As Long, j As Long, x As Long
Dim lns As Long, itms As Long, itm As Variant, v1 As Variant, v2 As Variant
Set fso = CreateObject("Scripting.FileSystemObject")
Set txt = fso.OpenTextFile(FILE_NAME)
dat = txt.ReadAll
If InStr(dat, DELIM) > 0 And InStr(dat, vbCrLf) > 0 Then
v1 = Split(dat, vbCrLf) 'split by lines
lns = UBound(v1) + 1
ReDim v2(1 To lns, 1 To UBound(Split(v1(0), DELIM))) 'setup final Range (array)
For i = 1 To lns 'parse each line
itm = Split(v1(i - 1), DELIM) 'split it by delimiter
itms = UBound(itm) + 1
If x < itms Then
x = itms
ReDim Preserve v2(1 To lns, 1 To x + 1) 'resize Range to fit
End If
For j = 1 To itms
v2(i, j) = itm(j - 1) 'copy values
Next
v2(i, x + 1) = "Total: " & itms 'show count
Next
With Sheet1.Range("A1").Resize(lns, x + 1)
.Value2 = v2
.EntireColumn.AutoFit
End With
End If
End Sub
(导入CSV后,区分它们可能为时已晚)