How do I have VB find and replace a string? 
Author Message
 How do I have VB find and replace a string?

Try this routine. I wrote it in VB5, but it should work in 4.0 with no
problems. It returns the number of replacements made in the string.

Public Function FindReplace(ByVal Text As String, ByVal Find As String,
ByVal ReplaceWith As String, RetString As String) As Integer

On Error Resume Next

Dim Offset As Integer, Offset2 As Integer
Dim NumFound As Integer
Dim Lg As Integer
Dim Str1 As String, Str2 As String

If Trim$(Text) = "" Then Exit Function

Lg = Len(Find)
NumFound = 0
RetString = ""

 Offset = InStr(1, Text, Find, vbTextCompare)
 If Offset = 0 Then Exit Do
 NumFound = NumFound + 1
 Str1 = Left$(Text, Offset - 1)
 Offset2 = InStr(Offset + Lg, Text, Find, vbTextCompare)
 If Offset2 = 0 Then
  Str2 = Mid$(Text, Offset + Lg)
  RetString = RetString & Str1 & ReplaceWith & Str2
  Exit Do
  Str2 = Mid$(Text, Offset + Lg, Offset2 - Offset - Lg)
  RetString = RetString & Str1 & ReplaceWith & Str2
 End If
 Text = Mid$(Text, Offset2)

FindReplace = NumFound

End Function

Ben Baird, MVP
Microsoft SiteBuilder Network Level 2
Visual Basic Thunder, v. 2.0
Common Controls Replacement Project, Official Member

>I have a small question.  I am using Visual Basic 4.0 to write programs,
and I
>was wondering how I could have visual basic search a string for a certain
>word, and replace it with a different word every time it found it in the
>string.  For example:

>I want to have the string to be:
>"This is a test because I am testing the program!! =)"

>and I want VB to replace the word "test" with "experiment" so it would

>"This is a experiment because I am experimenting the program!"

Sun, 03 Sep 2000 03:00:00 GMT  
 [ 6 post ] 

 Relevant Pages 

1. Find and Replace objects: Max len on the replace string

2. Replace and String.Replace only replaces first occurrence?

3. ADO Find with variable having an apostrophe in string

4. Find and Replace text in string

5. Find/replace characters in a string

6. Find and Replace(ing) string over 255characters

7. Find/replace a string that is in a table

8. Do a find/replace in code on *all* instances of the search string

9. String too long error in Find and Replace

10. SQL to Find and Replace String within a Field

11. Find and Replace Within a String

12. SQL to Find and Replace String within a Field


Powered by phpBB® Forum Software