簡體   English   中英

在記事本副本中搜索字符串,然后粘貼到特定條件

[英]Search a string in notepad copy and paste to certain criteria

我正在搜索宏,以在記事本中搜索字符串。 它應搜索字符串(“報告”)作為起始字符串,並應在(“報告結束”)中結束搜索。

Option Explicit

Sub ReadTxtFile()
    Dim start As Date
    start = Now

    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")

    Dim oFS As Object

    Dim filePath As String
    filePath = "C:\Users\Desktop\abc.txt "

    Dim arr(100000) As String
    Dim i As Long
    i = 0

    If oFSO.FileExists(filePath) Then
        On Error GoTo Err

        Set oFS = oFSO.OpenTextFile(filePath)
        Do While Not oFS.AtEndOfStream
            arr(i) = oFS.ReadLine
            i = i + 1
        Loop
        oFS.Close
    Else
        MsgBox "The file path is invalid.", vbCritical, vbNullString
        Exit Sub
    End If

    For i = LBound(arr) To UBound(arr)
        If InStr(1, arr(i), "report", vbTextCompare) Then
            Debug.Print i + 1, arr(i)
            Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
            Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)
        End If
    Next

    Debug.Print DateDiff("s", start, Now)

    Exit Sub

錯誤信息:

Err:
    MsgBox "Error while reading the file.", vbCritical, vbNullString
    oFS.Close
    Exit Sub

End Sub

在這里,我有搜索開始的代碼,但是它應該完成“報告的結尾”,因為結尾字符串會將我在文本中搜索到的內容全部復制並粘貼到新的記事本中。

我增強了部分代碼,使其包含兩點

(1)尋找“報告”和“報告結束”之間的內容

(2)將內容復制到名為xyz.txt的新.txt文件中,該文件已保存到我的Z:\\驅動器中

For i = LBound(arr) To UBound(arr)
    If InStr(1, arr(i), "report", vbTextCompare) Then

        'Declare variables for the new output file
        Dim sOutputFileNameAndPath As String
        Dim FN As Integer
        sOutputFileNameAndPath = "Z:\xyz.txt"
        FN = FreeFile

        'Open new output file
        Open sOutputFileNameAndPath For Output As #FN


        'While 'end of report' has not been found, 
        'keep looping to print out contents starting from 'report'
        Do While InStr(1, arr(i), "end of report", vbTextCompare) = 0

            Debug.Print i + 1, arr(i)
            Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
            Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

            'Print into new output file
            Print #FN, i + 1 & " " & arr(i)

            'increment count
            i = i + 1

        Loop

        'Print out the 'end of report' line as well
        Debug.Print i + 1, arr(i)
        Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
        Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

        'Print 'end of report' line into new output file as well
        Print #FN, i + 1 & " " & arr(i)

        'close the new output file
        Close #FN

        'exit the 'For..Next' structure since 'end of report' has been found
        Exit For


    End If

Next

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM