Library code snippets

Replace text in textbox or file

This is a simple text replacement example. It will also work on Binary files since I included the description on how to make it reusable from a form with 3 text boxes and how to read in a full binary or ascii file as a single string. Usage:

Private Sub cmdReplaceText_Click()
    'replaces all occurances of Text2 in Text1 with Text3
    Call ReplaceTextInTextBox(Text1, Text2, Text3)
End Sub
Private Sub cmdReplaceFile_Click()
    'replaces all occurances of "hello" with "goodbye" in c:\test.txt, and saves the new file as c:\test_replace.txt
    Call ReplaceInFile("c:\test.txt", "c:\test_replace.txt", "hello","goodbye")
End Sub

Place the code below in a module

Public Function ReplaceTextInTextBox(MyTextBox As Object,_
TextOld As Object, TextNew As Object) 'The object reference is made form the form 'you use to call this module. 'Assumed you have a text1, text2 and text3 text box on your form 'where 1 is used for the text you wish to replace text in '2 is the one containing text you are searching for '3 is the new text you wish to see entered in its place. 'The replacement function being called Call ReplaceText(MyTextBox.Text, TextOld.Text, TextNew.Text) 'Replace textview and refresh your form MyTextBox.Text = ReturnValue MyTextBox.Refresh End Function Public Function ReplaceInFile(InputFile As String, _ OutputFile As String, OldT As String, NewT As String) As String Dim Fnum As Integer ' get a FreeFile number Dim FileLength As Long 'Just in case its really big Dim TheString As String
'I open the file as binary to avoid some 'complications with reading in a full file. 'This just so I can skip some trouble shooting with 'some special characters in certain exe files. 'It might be that character you wish to replace. Fnum = FreeFile Open InputFile For Binary As #Fnum ' Open file. FileLength = LOF(Fnum) ' Get length of file. TheString = Input(FileLength, #Fnum) Close #Fnum ' Close file. 'OldT = Whatever text you send form a form or function to search for 'NewT = Whatever text you wish to replace OldT with 'Call the function to replace text Call ReplaceText(TheString, OldT, NewT) 'Now print the result to a new file 'so you dont overwrite your original Fnum = FreeFile Open OutputFile For Output As #Fnum ' Open file. Print #Fnum, ReturnValue ' the ReturnValue from the replacement Close #Fnum ' Close file. End Function Public Function ReplaceText(CleanThis As String, _ OldText As String, _ NewText As String) 'To get the len of the string Dim StrLn As Long 'To split the string Dim PartA As String, PartB As String 'If search string is found, get its start position Dim FoundP As Long Dim OldLn As Long On Error GoTo ErrHandle 'Set a value for the len of the old text to be replaced OldLn = Len(OldText) StrLn = Len(CleanThis) 'Loop through the string until all occurences are eliminated Do While InStr(1, CleanThis, OldText) <> 0 FoundP = InStr(1, CleanThis, OldText) 'Get PartA of the string (before found occurance) PartA = Left(CleanThis, FoundP - 1) 'Get PartB of the string (after found occurance) PartB = Right(CleanThis, StrLn - FoundP - OldLn + 1) '*NOTE ON THE ADDITION AND SUBTRACTION** '****************************************************** '+ 1 to avoid a skip in adding found len and old len 'The previous line could also be written ' 'PartB = Right(CleanThis, StrLn - (FoundP + OldLn - 1)) '****************************************************** 'REBUILD THE STRING BEFORE NEXT LOOP 'This adds a space before and after NewText 'and trims out unneccessary spaces too! CleanThis = Trim(PartA) & " " & _ Trim(NewText) & " " & _ Trim(PartB) 'GET NEW LEN BEFORE LOOPING StrLn = Len(CleanThis) Loop 'Set result of the function ReplaceInString = CleanThis 'Avoid error handling Exit Function 'Add your own error code hereafter ErrHandle: Select Case Err.Number Case Err.Number MsgBox "Your function executed with an error " & Err.Number _
& vbCrLf & vbCrLf & Err.Description, vbExclamation, _
"Error " & Err.Number Err.Clear End Select Resume Next End Function

Comments

  1. 22 Sep 2008 at 12:00

    Yeahhhhh... You could use that, OR...

     

        Public Function Replace(ByVal TextToReplace As String)
            Try
                TextBox1.Text = TextBox1.Text.Replace(TextToReplace.ToString, "") 'Replace the string with nothing
            Catch ex As Exception
                Throw ex
            End Try
        End Function

     

    'Usage Below

    Replace(".exe","") 'Replaces .exe with nothing - I origionally used this for multiple process killing =)

     

    -Recon92

  2. 15 Jul 2004 at 13:35

    I am certain it would crash in a file of that size.
    I am looking into getting a code that will do it for a 16 Gb file right now so I'm in the same boat as you

  3. 30 Jul 2003 at 16:36

    Uh...just ran this code through VB and it doesn't work.  I'll have to make some changes to get it to work.  It's a good idea to replace text in a file, but for LARGE files (I normally deal with ext files that are 70,000+ pages when printed out) I think this app would crash and burn.  Just my opinion
    -- Joe --

  4. 01 Jan 1999 at 00:00

    This thread is for discussions of Replace text in textbox or file.

Leave a comment

Sign in or Join us (it's free).

Mike J

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

We'd love to hear what you think! Submit ideas or give us feedback