我正在尝试将 txt 文件中的所有行提取到 Excel 中。不幸的是,我最终使用的脚本仅返回第一行,我看不到需要修改的内容。你能帮我调整一下代码吗?
myFile = Dir(myPath & "*.txt")
rowNum = 1
Do While myFile <> ""
fileNum = FreeFile
Open myPath & myFile For Input As #fileNum
Do Until EOF(fileNum)
Line Input #fileNum, textLine
newSheet.Cells(rowNum, 1).Value = textLine
rowNum = rowNum + 1
Loop
Close #fileNum
myFile = Dir
Loop
我过去尝试这样做时遇到了问题。我不得不采取一种不太花哨但可行的解决方法:我将“.txt”文件重命名为“.csv”,并使用 Excel 中的“数据>>文本到列”工具。最后,我将数据复制并粘贴到最终的 Excel 工作表中。
如果你确实需要自动化,也许你可以尝试Python。使用 Python,我可以轻松地读取和写入 Excel 文件。特别是关于写作,我建议你看看这里: 如何使用openpyxl写入xlsm
希望这对您有帮助。
因此,可以通过多种方式使用 Excel 本身导入文件数据,并且无需编码。
但是,如果你因为某些原因想要使用VBA(例如因为你想对内容做一些修改),你可以使用下面的函数。它将一次性读取整个文件的内容并返回一个字符串数组。
Function readTextFile(filename As String)
Dim f As Integer, inputBuffer As String
f = FreeFile
Open filename For Binary Access Read As #f
inputBuffer = Space(LOF(f)) ' Size Buffer so that get reads all at once
Get #f, , inputBuffer
Close #f
' Replace all possible line endings with vbLf
inputBuffer = Replace(inputBuffer, vbCrLf, vbLf)
inputBuffer = Replace(inputBuffer, vbCr, vbLf)
' Create an array of lines
readTextFile = Split(inputBuffer, vbLf)
End Function
您可以在代码中使用它:
myFile = Dir(myPath & "*.txt")
rowNum = 1
Do While myFile <> ""
Dim lines, lineNo As Long
lines = readTextFile(myPath & myFile)
For lineNr = 0 To UBound(lines)
newSheet.Cells(rowNum, 1).Value = lines(lineNr)
rowNum = rowNum + 1
Next
Loop