【发布时间】:2021-12-13 04:10:41
【问题描述】:
我的 Excel 读取 CSV 文件以获取网格表的数据。
"header", "header", "header", "header"
"value1",
"value2", "value3", "value4"
"value5", "value6", "value7", "value8"
"value9", "value10", "value11", "value12"
我想读取 CSV 的第二行和第三行作为网格表的第一行。 其他行一一读取。
我的代码是:
Dim FileName As String, folder As String
folder = ThisWorkbook.Path & "\"
FileName = Dir(ThisWorkbook.Path & "\*.csv")
With ActiveSheet.QueryTables _
.Add(Connection:="TEXT;" & folder & FileName, Destination:=ActiveCell)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
我的方法: 我正在尝试用一个新文件修改 csv 文件,该文件将第二行和第三行合并为第二行。
filePath = folder & fileName
Dim fName As String, fso As Object, fsoFile As Object, txt As Variant
Set fso = CreateObject("Scripting.FileSystemObject")
Set fsoFile = fso.OpenTextFile(filePath, 1)
txt = fsoFile.ReadAll
fsoFile.Close
txt = Split(txt, vbNewLine)
txt(2 - 1) = "some text with special characters like & Char(44) & and & Chr(10) & and so on"
Set fsoFile = fso.OpenTextFile(filePath, 2)
fsoFile.Write Join(txt, vbNewLine)
fsoFile.Close
问题是网格表在单元格内将特殊字符显示为 & Char(44) & 和 & Char(10) &...
【问题讨论】:
-
您的第二行在 Column1 中只有一个条目。如果你使用 Power Query,你可以
Transpose=>Merge the first two columns with Linefeed as the separator =>Transpose=>Use first row as headers -
我无法使用 Power Query
-
为什么不呢?您可以编辑连接字符串来完成相同的任务。您使用的是哪个版本的 Excel?
-
我正在使用 Excel 2019。
-
如果您有 Windows Excel 2019,那么您应该有 Power Query。在“数据”选项卡上它可能被称为
Get & Transform。