Visual Basic > Strings
Search for a specific string and replace it with another
Search for a specific string and replace it with another ' SearchLine is input, SearchFor is what to search for, ReplaceWith is the replacement Function sReplace(SearchLine as String, SearchFor as String, ReplaceWith as String) Dim vSearchLine as String, found as Integer found = InStr(SearchLine, SearchFor): vSearchLine = SearchLine If found <> 0 Then vSearchLine = "" If found > 1 Then vSearchLine = Left(SearchLine, found - 1) vSearchLine = vSearchLine + ReplaceWith If found + Len(SearchFor) - 1 < Len(SearchLine) Then _ vSearchLine = vSearchLine + Right$(SearchLine, Len(SearchLine) - found - Len(SearchFor) + 1) end If sReplace = vSearchLine End Function * another routine * Only 17 lines of code for a super-fast find-and-replace function: -- start code -- ' Copy *both* functions to VBScript or VB application: ' FindReplace and ReplaceFirstInstance ' Function FindReplace(SourceString, SearchString, ReplaceString) tmpString1 = SourceString do Until vFixed tmpString2 = tmpString1 tmpString1 = ReplaceFirstInstance(tmpString1, SearchString,ReplaceString) If tmpString1 = tmpString2 Then vFixed = True Loop FindReplace = tmpString1 end Function Function ReplaceFirstInstance(SourceString, SearchString, ReplaceString) FoundLoc = InStr(1, SourceString, SearchString) If FoundLoc <> 0 Then ReplaceFirstInstance = Left(SourceString, FoundLoc - 1) & _ ReplaceString & Right(SourceString, _ Len(SourceString) - (FoundLoc - 1) - Len(SearchString)) Else ReplaceFirstInstance = SourceString end If end Function --- end code - Just to clarify, one function is used to go through the entire string and replace all instances of the search string ("Replace All"). The other function is used to only replace the first instance of the search string ("Replace"). The former loops the latter until there are no more instances of the search string. > Function FindReplace(SourceString, searchstring, replacestring) tmpString1 = SourceString do Until vFixed tmpString2 = tmpString1 tmpString1 = ReplaceFirstInstance(tmpString1, searchstring, replacestring) If tmpString1 = tmpString2 Then vFixed = True loop FindReplace = tmpString1 End Function Function ReplaceFirstInstance(SourceString, searchstring, replacestring) Static StartLoc '* If StartLoc = 0 Then StartLoc = 1 '* FoundLoc = InStr(StartLoc, SourceString, searchstring) '* If FoundLoc <> 0 Then ReplaceFirstInstance = Left(SourceString, FoundLoc - 1) & _ replacestring & Right(SourceString, _ Len(SourceString) - (FoundLoc - 1) - Len(searchstring)) StartLoc = FoundLoc + Len(replacestring) '* Else StartLoc = 1 '* ReplaceFirstInstance = SourceString end If End Function Return
Visual Basic Codes
ActiveX
Miscellaneous
Applications
Code Snippets
Common Dialogs
Special Effects
Database Stuff
Date Time
Files Drives
Forms
Graphics Games
Internet Stuff
Multimedia
Other
Strings
Windows