vb如何判断文本文档中某一行字符串所在行数并获取

2025-05-08 05:45:08
推荐回答(2个)
回答1:

示例附件中,日记文件放在C:\如在其它位置自行修改代码

Private Sub Command1_Click()
Dim h As Long, LTxt As String, spstr As Variant, MaxDate As Date, FindLine As Long
h = FreeFile
Dim n As Long, tmp As Date
Open "c:\日记.txt" For Input As h
Do While Not EOF(h)
    Line Input #h, LTxt
    n = n + 1
    spstr = Split(LTxt, ":")
    If UBound(spstr) = 1 Then
        If Trim(spstr(0)) = "日期" Then
            If IsDate(spstr(1)) Then
                tmp = CDate(spstr(1))
                If tmp > MaxDate Then MaxDate = tmp: FindLine = n
            End If
        End If
    End If
Loop
Close
If FindLine = 0 Then
    MsgBox "未找到存在日期的行"
Else
    MsgBox "找到最后的日期:" & MaxDate & "  在文件第 " & FindLine & " 行"
End If
End Sub


回答2:

Private Sub Command1_Click()Dim h As Long, LTxt As String, spstr As Variant, MaxDate As Date, FindLine As Longh = FreeFileDim n As Long, tmp As DateOpen "c:\日记.txt" For Input As hDo While Not EOF(h) Line Input #h, LTxt n = n + 1 spstr = Split(LTxt, ":") If UBound(spstr) = 1 Then If Trim(spstr(0)) = "日期" Then If IsDate(spstr(1)) Then tmp = CDate(spstr(1)) If tmp > MaxDate Then MaxDate = tmp: FindLine = n End If End If End IfLoopClose hIf FindLine = 0 Then MsgBox "未找到存在日期的行"Else MsgBox "找到最后的日期:" & MaxDate & " 在文件第 " & FindLine & " 行"End IfEnd Sub