View Full Version : [SOLVED:] Need help in searching last occurrence of string in text file
sam2211
09-10-2008, 10:04 AM
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.
Oorang
09-12-2008, 07:12 PM
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
sam2211
09-13-2008, 07:17 AM
:bow:  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.....:thumb 
 
:beerchug:  Thanks again......
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.