Consulting

Results 1 to 3 of 3

Thread: Need help in searching last occurrence of string in text file

  1. #1
    VBAX Newbie
    Joined
    Sep 2008
    Posts
    2
    Location

    Need help in searching last occurrence of string in text file

    Hi ,

    I am not good in file handling in excel macro..i need some help from
    u.
    I have one huge text file and i want to search last occurrence of
    string in that file and then cut the data after that searched line
    till end of file and paste it into a new text file.

    Any help appreciated. thanks in advance.

  2. #2
    You have actually asked for a couple of tasks, I broke them down in the example. Post back if you have questions:
    Option Explicit
    
    Public Sub Example()
        Dim strFileText As String
        Dim strFinalValue As String
        strFileText = GetFileText("C:\Test\MyTextFile.txt")
        strFinalValue = ExtractTextAfter(strFileText, "bar", vbTextCompare)
        MsgBox strFinalValue
    End Sub
    
    Private Function GetFileText(ByVal filePath As String) As String
        Dim lngFileNum As Long
        Dim lngFileLen As Long
        Dim strFileText As String
        lngFileNum = FreeFile
        Open filePath For Binary Access Read Shared As #lngFileNum
        lngFileLen = FileLen(filePath)
        strFileText = String$(lngFileLen, vbNullChar)
        Get #lngFileNum, , strFileText
        Close #lngFileNum
        GetFileText = strFileText
    End Function
    
    Private Function ExtractTextAfter(ByVal stringValue As String, ByVal subStringValue As String, _
        Optional ByVal compare As VbCompareMethod = VbCompareMethod.vbBinaryCompare) As String
        Dim lngDPos As Long
        Dim strRtnVal As String
        lngDPos = InStrRev(stringValue, subStringValue, -1, compare)
        If lngDPos Then
            strRtnVal = Mid$(stringValue, lngDPos + Len(subStringValue))
        End If
        ExtractTextAfter = strRtnVal
    End Function
    Last edited by Aussiebear; 02-01-2025 at 08:43 AM.
    Cordially,
    Aaron



    Keep Our Board Clean!
    • Please Mark your thread "Solved" if you get an acceptable response (under thread tools).
    • Enclose your code in VBA tags then it will be formatted as per the VBIDE to improve readability.

  3. #3
    VBAX Newbie
    Joined
    Sep 2008
    Posts
    2
    Location

    Re: 'Need help in searching last occurrence of string in text file'

    Its Great Oorang, thanks for ur time...
    It is working 99% fine...
    can we delete the data that is coming in message box from original file and create a new text file and paste there.....

    Thanks again......

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •