Subscribe:Posts Comments

You Are Here: Home � � Replace String

Function to replace string :

Public Function ReplaceString(ByVal pString As String, ByVal Keyword As String, ByVal NewKeyWord As String) As String
Dim StrLen As Integer
Dim StrOut As String
Dim KeyPos As Integer
Dim StrLenChange As Boolean
Dim StartPos As Integer

' set a few values before we go any further
StartPos = 1
StrLen = Len(pString)

' if the word to replace and the word to replace by are different lengths, record that they are
If Len(Keyword) <> Len(NewKeyWord) Then StrLenChange = True

' check to see where the first occurence of the keyword to replace is in the string
KeyPos = InStr(StartPos, pString, Keyword)

' only do the replace loop if the keyword string is there
While KeyPos > 0
' rebuild the string, taking out the keyword and replacing it with the NewKeyword
pString = Left(pString, KeyPos - 1) & NewKeyWord & Mid(pString, KeyPos + Len(Keyword), StrLen - KeyPos - Len(Keyword) + 1)

' if the Keyword and NewKeyword as different lengths then recalc the length of the string
If StrLenChange Then StrLen = Len(pString)

' calculate the position where we should start looking to see if the KeyWord is in the string
StartPos = KeyPos + Len(NewKeyWord)

' check to see where the next occurence of the keyword to replace is in the string
KeyPos = InStr(StartPos, pString, Keyword)
Wend

' return the string
ReplaceString = pString

End Function
Tags:

0 comments

Leave a Reply