VBA.Replace is not declare code example

Example: excel vba replace part of a string

'VBA function to replace a substring... if it exists in the full
'string. Checking to see if it exists is very quick. Replacing is
'slow by comparison. So it is wise to check first:

Function IfInReplace$(s$, substr1$, replacement$, Optional CaseSensitivity = vbTextCompare)
    If InStr(1, s, substr1, CaseSensitivity) Then s = Replace(s, substr1, replacement, , , CaseSensitivity)
    IfInReplace = s
End Function

'---------------------------------------------------------------------------------------------------

MsgBox IfInReplace("abc123def", "123", "")    '<--displays: abcdef

Tags:

Vb Example