Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleReplace occurrences of a string in another (like VB6's Replace function)
Description
Keywordsreplace, find
CategoriesStrings
 
Visual Basic 6 provides a very convenient Replace function but Replace is not available in previous versions of Visual Basic or in VBA. This function replaces occurrences of a target string with a new string.
 
' Replace all occurrances of from_str with to_str.
Public Function ReplaceText(ByVal txt As String, ByVal _
    from_str As String, ByVal to_str As String) As String
Dim result As String
Dim from_len As Integer
Dim pos As Integer

    from_len = Len(from_str)
    Do While Len(txt) > 0
        ' Find from_str.
        pos = InStr(txt, from_str)
        If pos = 0 Then
            ' No more occurrences.
            result = result & txt
            txt = ""
        Else
            ' Make the replacement.
            result = result & Left$(txt, pos - 1) & to_str
            txt = Mid$(txt, pos + from_len)
        End If
    Loop

    ReplaceText = result
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated