1

我正在编写一个非常简单的解析器来将文本文件读入 Excel。文件超出了 Excel 2012 中的可用行数,因此我必须采用逐行方法。

我已经测试了 Microsoft Scripting Runtime Library、TextStream Object 和 ReadLine 方法。

就我将 CRLF 作为行尾的 Windows 文件而言,它工作正常,而当只有 LF 标记行尾时它会失败。

我在 VBA 之外看到了很多解决方案,在 VBA 中是否有任何可行的解决方案?

提前致谢

4

3 回答 3

0

Start by making with a test file that uses only LFs as line endings in c:\temp\lfs.txt

This will read the file into a string:

Dim FileNum As Integer
Dim sBuf As String
Dim sTemp As String

 FileNum = FreeFile
 Open "c:\temp\lfs.txt" For Input As FileNum

 While Not EOF(FileNum)
     Line Input #FileNum, sBuf
     sTemp = sTemp & sBuf
 Wend

 Close FileNum

' Now, what do we have?  First the string itself:
Debug.Print sTemp
' Are there any CRs in it?  
Debug.Print Replace(sTemp, vbCr, "CR")
' LFs?
Debug.Print Replace(sTemp, vbLf, "LF")
' Replace the LFs with CRLFs:
Debug.Print Replace(sTemp, vbLf, vbCrLf)

Now if you write it back out to file, you should be able to use it
于 2013-03-23T17:48:36.593 回答
0

我使用了以下由 LF 分隔的非常简单的文本文件。以下 vba 代码对我有用。也许您可以在 TextStream.ReadLine 方法失败的地方发布文本文件数据的简短示例?

在此处输入图像描述

Private Const TEXT_FILE_PATH As String = "C:\Temp\VBA\textFileForUnix.txt"

Public Sub test()
    Dim targetSheet As Worksheet
    Set targetSheet = ThisWorkbook.ActiveSheet
    ReadText sheet:=targetSheet, textFilePath:=TEXT_FILE_PATH
End Sub

Private Sub ReadText(ByRef sheet As Worksheet, ByRef textFilePath As String)
    Dim scriptingFileSystem As Scripting.FileSystemObject
    Dim scriptingFile As Scripting.File
    Dim scriptingStream As Scripting.TextStream

    Set scriptingFileSystem = New Scripting.FileSystemObject
    Set scriptingFile = scriptingFileSystem.GetFile(textFilePath)

    Set scriptingStream = scriptingFile.OpenAsTextStream(ForReading)
    Dim r As Long
    Dim c As Byte
    With scriptingStream
        r = 1
        c = 1
        Do While Not .AtEndOfStream
          sheet.Cells(r, c).Value = .ReadLine
          r = r + 1
        Loop
       .Close
    End With

    Set scriptingFile = Nothing
    Set scriptingFileSystem = Nothing
End Sub
于 2013-03-24T09:06:34.587 回答
0

这个单行将修复我遇到的任何“不寻常”的行尾,以实现正确的 CRLF。特别是它会修复单个 LF 或单个 CR 或 LF-CR。

 result$ = Replace(Replace(Replace(Replace(Replace(txt$, vbLf & vbCr, vbLf), vbCrLf, vbLf), vbLf, vbCrLf), vbCr, vbCrLf), vbCrLf & vbLf, vbCrLf)
于 2021-01-08T13:29:27.060 回答