简体   繁体   English

如何使用 VBA 逐行读取文本文件并放入 excel 表格单元格? 读取线不工作

[英]How can i read a text file line by line and put into excel sheet cell using VBA? Read line is not working

I am using the below code.我正在使用下面的代码。 Instead of putting the data line by line into cells, it is putting all data into one cell.它不是将数据逐行放入单元格中,而是将所有数据放入一个单元格中。 attached image for your reference.附上图片供您参考。 Also attached the sample text file that I am reading.还附上了我正在阅读的示例文本文件。 please note, when I try to open this text file in Wordpad & save it, then it works fine.请注意,当我尝试在写字板中打开此文本文件并保存它时,它可以正常工作。

Click here to download sample txt file that is having this issue 单击此处下载存在此问题的示例 txt 文件

此代码输出

 Sub Test_ReadFromTxtToArray()

 Dim FSO As Object, MyFile As Object
 Dim FileName As String, Arr As Variant

 FileName = "C:\Test\O0000540.txt" ' change this to your text file full name
 Set FSO = CreateObject("Scripting.FileSystemObject")
 Set MyFile = FSO.OpenTextFile(FileName, 1)
 Arr = Split(MyFile.ReadAll, vbCrLf) ' Arr is zero-based array


 'For test
 'Fill column A from this Array Arr

 Sheet2.Range("A1").Resize(UBound(Arr) + 1, 1).Value = Application.Transpose(Arr)

End Sub

It happens that the file you provided for download has LF as the EOL , so your Split method is not splitting anything.碰巧您提供的下载文件具有LF作为EOL ,因此您的Split方法不会拆分任何内容。

But what if you don't know the EOL?但是,如果您不知道 EOL 怎么办?

This should work:这应该有效:

S = MyFile.readall
 
 S = Replace(S, vbCrLf, vbLf)
 S = Replace(S, vbCr, vbLf)

 Arr = Split(S, vbLf)

In other words, change whatever might be there to a known EOL, then split on that.换句话说,将可能存在的任何内容更改为已知的 EOL,然后对其进行拆分。 You might need to do something different for the MAC.您可能需要为 MAC 做一些不同的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM