Excel VBA – 如何逐行读取csv文件,但不是整个文件
这是我需要阅读的csv文件内容:
"header", "header", "header", "header", "header", "header" "value", "value", "", "value", "value", "" "value", "value", "value", "value", "value", ""
我在网上find了导入文件的代码:
Sub ImportCSVFile(ByVal filePath As String, ByVal ImportToRow As Integer, ByVal StartColumn As Integer) Dim line As String Dim arrayOfElements Dim element As Variant Open filePath For Input As #1 ' Open file for input Do While Not EOF(1) ' Loop until end of file ImportToRow = ImportToRow + 1 Line Input #1, line arrayOfElements = Split(line, ";") 'Split the line into the array. 'Loop thorugh every element in the array and print to Excelfile For Each element In arrayOfElements Cells(ImportToRow, StartColumn).Value = element StartColumn = StartColumn + 1 Next Loop Close #1 ' Close file. End Sub
由于某种原因,我还没有想出,该代码不逐行读取,但在这一行的整个文件
Line Input #1, line
有人可以解释为什么它不工作?
只是fyr,我做了什么来纠正Lf终结者到CrLf终结者
Private Sub Correct_Lf_to_CrLf(ByVal FilePath As String) Dim DataLine As String Open Environ("TEMP") & "\temp.txt" For Output As #1 Open FilePath For Input As #2 While Not EOF(2) Line Input #2, DataLine Print #1, Replace(DataLine, vbLf, vbNewLine) Wend Close #2 Close #1 'NOTE: Your original file will be replaced with the new file ' where Lf are replaced with CrLf, amend where it is appropriate. FileSystem.FileCopy Environ("TEMP") & "\temp.txt", FilePath End Sub
仅供参考: vbNewLine
是vbCrLf