gpt4 book ai didi

vba - 如何读取文本文件中的倒数第二行

转载 作者:行者123 更新时间:2023-12-04 20:13:41 24 4
gpt4 key购买 nike

我想在 VBA 中读取一个大文件并在线看到此代码:

Dim MyChar As String, Pointer As Long, LastLine As String
Open "MyTextFile.Txt" For Binary As #1
Pointer = LOF(1) - 2
MyChar = Chr$(32)
Do
Get #1, Pointer, MyChar
If MyChar = vbCr Or MyChar = vbLf Then
Exit Do
Else: Pointer = Pointer - 1
LastLine = MyChar & LastLine
End If
Loop
MsgBox "Last Line is " & LastLine

如何更改此代码以获取倒数第二行?在这方面需要一些帮助。

想到了这个:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
"MyTextFile.Txt", 1)
objTextFile.ReadAll
MsgBox objTextFile.Line

但我无法到达 2 号线。

最佳答案

您提供的代码如下:

  • 它设置一个指向文件的最后一个字符的指针
  • 然后它向后读取该文件,直到找到换行符
  • 它返回所有读取的内容作为最后一行。

  • 为了根据您的需要修改它,我添加了 Boolean secondRun ,这让代码再次运行第 2 步,从而记录最后第二行:
    Dim MyChar As String, Pointer As Long, LastLine As String
    Open "MyTextFile.Txt" For Binary As #1
    Pointer = LOF(1) - 2
    MyChar = Chr$(32)
    Dim secondRun As Boolean
    Do
    ' Read character at position "Pointer" into variable "MyChar"
    Get #1, Pointer, MyChar
    If MyChar = vbCr Or MyChar = vbLf Then ' Linebreak = line read completely
    If Not secondRun Then
    ' Run again if we've read only one line so far
    secondRun = True
    LastLine = ""
    Pointer = Pointer - 2
    Else
    Exit Do
    End If
    Else: Pointer = Pointer - 1
    ' Add character to result String
    LastLine = MyChar & LastLine
    End If
    Loop
    MsgBox " 2nd last line is " & LastLine

    关于vba - 如何读取文本文件中的倒数第二行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32819266/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com