Friday, 7 January 2011

MS Access - Replacing Part of a String

Had another issue where we needed to replace a section of a string with another input string, here is the function I came up with.

to use it you need to enter three elements, 1) the String to be changed, 2) The Part to be Removed, 3) The String to Replace it.

so for example ReplaceString("This is the Start","Start","End") Where the String is "This is the Start" and the function will replace "Start" with "End" so that the Output of the Above function is "This is the End"

Function ReplaceString(ByVal strString As String, ByVal strOld As _
String, ByVal strNew As String) As String


Dim lngCount As Long
Dim strChange As String

strChange = strString
lngCount = InStr(strChange, strOld)

Do While lngCount > 0
strChange = Left(strChange, lngCount - 1) & Replacevalue & _
Mid(strChange, lngCount + Len(strOld))
lngCount = InStr(lngCount + Len(strNew), strChange, strOld, 1)
Loop

ReplaceString = strChange

End Function

No comments:

Post a Comment