我正在使用 VBA將此 CSV加載到 Excel。我正在使用CSV Lint驗證 CSV,但出現三個換行錯誤。
我的代碼是:
Dim ws As Worksheet
Set ws = ActiveSheet
Dim fileName As String, folder As String
folder = ThisWorkbook.Path & "\"
fileName = Dir(ThisWorkbook.Path & "\*.csv")
ActiveCell.Offset(1, 0).Range("A6").Select
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 檔案修改為新檔案的情況下洗掉換行符?我嘗試了很多宏,但似乎沒有任何效果。
如果我必須將 CSV 修改為新的,我有以下代碼:
Dim fso As Object, tsIn, tsOut
Dim s As String
Dim filePath As String
Dim newCSV As String
filePath = folder & fileName
newCSV = folder & "report.csv"
Set fso = CreateObject("Scripting.Filesystemobject")
Set tsIn = fso.OpenTextFile(filePath, 1)
Set tsOut = fso.CreateTextFile(newCSV, 1)
Do While tsIn.AtEndOfLine <> True
s = tsIn.readline
s = Replace(s, vbCrLf, "")
tsOut.write s
Loop
tsIn.Close
tsOut.Close
Kill filePath
但它會洗掉 CSV 檔案中的所有換行符。
如何搜索影響 Excel 的換行符?
uj5u.com熱心網友回復:
CSV 規范RFC4180 規定一個要求是:
- 以 (
CR/LF) 字符結尾的 MS-DOS 樣式行(最后一行可選)。
這已在“如何撰寫 CSV”部分中為您的 CSS Linter確認。
(另請參閱“常見錯誤”部分。)
行結尾使用
CRLF(Windows 行結尾),列名和欄位用逗號分隔。
您的代碼似乎正在洗掉CRLF。
您的示例 CSV 似乎使用 LF(基于我從您的鏈接復制/粘貼到Notepad 并轉到“查看→顯示符號→顯示所有字符”)。
因此,我認為您需要將您的Replace線路替換為:
s = Replace(s, vbLf, vbCrLf)
uj5u.com熱心網友回復:
將 CSV 作為作業簿打開并將資料復制到活動作業表中。任何參考的換行符都將出現在單元格中。
Option Explicit
Sub loadcsv()
Dim ws As Worksheet, wbCSV As Workbook, n As Long
Dim fileName As String, folder As String
folder = ThisWorkbook.Path & "\"
fileName = Dir(folder & "*.csv")
Set ws = ActiveSheet
Set wbCSV = Workbooks.Open(folder & fileName, False, True)
With wbCSV.Sheets(1)
n = .UsedRange.Rows.Count
.UsedRange.Copy ws.Range("A7")
End With
wbCSV.Close False
ws.Columns("A:T").AutoFit
ws.Rows("7").Resize(n).AutoFit
MsgBox n & " rows loaded from " & folder & fileName, vbInformation
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/345273.html
上一篇:對范圍定義中的列使用變數
