Skip Navigation Links.
Seach/Replace Routine
Language(s):Visual Basic 6.0
Category(s):Search/Replace

General purpose search/replace routine for strings.

' Seach/Replace Routine 

' General purpose search/replace routine for strings. 

' Jon Vote 

' 02/2002 
'
' 1) Create a new project. Form1 will be created by default.
' 2) Stack three Label, Textbox pairs such that each Label has a Textbox to it's right.
' 3) Be sure that Label1 is next to Text1, Label2 next to Text2 and Label3 next to Text3.  
' 4) Add a Command Button below the Label, Textbox pairs. 
' 5) Paste the following code into the declarations section of Form1:

' --- Begin code for Form1

' Search/Replace Example
'
' General Purpose Search/Replace Routine
'
' Jon Vote, Idioma Software Inc. 
'
' 02/2002

' www.idioma-software.com 
'
Option Explicit

Private Sub Command1_Click()
  
  Dim strMessage As String
  
  strMessage = "Searching: " & Text1.Text & vbCrLf
  strMessage = strMessage & "For: " & Text2.Text & vbCrLf
  strMessage = strMessage & "Replace with: " & Text3.Text & vbCrLf & vbCrLf
  strMessage = strMessage & "Result: " & SearchReplace(Text1.Text, Text2.Text, Text3.Text)
    
  MsgBox strMessage
  
End Sub

Private Sub Form_Load()
 
  Me.Caption = "Search/Replace Example"
  
  Label1.Caption = "Search:"
  Label2.Caption = "For:"
  Label3.Caption = "Replace With:"
  
  Text1.Text = "Hoooooowser"
  Text2.Text = "oooooows"
  Text3.Text = "Oz"
  
End Sub

Function SearchReplace(ByVal strSearchWhat As String, ByVal strSearchFor As String, ByVal strReplaceWith As String) As String

' Search/Replace
' returns result
' Example strSearchWhat     = "Hoooooowser"
'         strSearchFor = "oooooows"
'         strReplaceWith = "Oz"
' Returns HOzer
'

Dim lnStr As Long
Dim lnRW As Long
Dim lnSF As Long
Dim s As Long
Dim t As Long
Dim sTemp As String

lnStr = Len(strSearchWhat)
lnRW = Len(strReplaceWith)
lnSF = Len(strSearchFor)

If strSearchFor = "" Then
  SearchReplace = strSearchWhat
Else
    t = 1
    s = InStr(t, strSearchWhat, strSearchFor)
    Do While s > 0
      sTemp = Left$(strSearchWhat, s - 1) & strReplaceWith
      If s < lnStr Then
        strSearchWhat = sTemp & Mid$(strSearchWhat, s + lnSF)
        t = s + lnRW
        lnStr = Len(strSearchWhat)
        s = InStr(t, strSearchWhat, strSearchFor)
      Else
        strSearchWhat = sTemp
        s = 0 ' close loop
      End If
    Loop
    
    SearchReplace = strSearchWhat
    
End If

End Function

' --- End code for Form1 ---



This article has been viewed 3419 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.