vba replace
' Replace into string
Sub TestMe()
Debug.Print Replace("a,B,c,d,e", ",", "-") 'a,B,c,d,e -> a-B-c-d-e
Debug.Print Replace("Mr XXX", "XXX", "Bond") 'Mr XXX -> Mr Bond
Debug.Print Replace("a,b,c,d,e", ",", "-", 3, 2) 'a,B,c,d,e -> b-c-d,e
End Sub
4.11
9
'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
Thank you!
9
0
3.2
5
'VBA function to make multiple replacements in a template string:
Function TemplateReplace$(template$, ParamArray replacements())
Dim c&, s$, t$, e
s = template
For Each e In replacements
c = c + 1
t = "|%" & c & "|"
If InStrB(e, "~~") Then e = Replace(e, "~~", Chr(34))
If InStrB(s, t) Then s = Replace(s, t, e)
Next
TemplateReplace = s
End Function
'--------------------------------------------------------------------
Const TEMPLATE = "SELECT * FROM |%1| WHERE (survived = |%2|)"
MsgBox TemplateReplace$(TEMPLATE, "titanic", "~~true~~")
'Displays: SELECT * FROM titanic WHERE (survived = "true")
Thank you!
5
0
Are there any code examples left?
New code examples in category VBA
-
VBA 2022-03-27 20:55:02 excel vba check if all substrings in list are in string
-
VBA 2022-03-27 20:40:39 excel vba set cell value to empty
-
VBA 2022-03-27 17:05:52 vba simple quote
-
VBA 2022-03-27 14:30:19 textbox find and replace vb
-
VBA 2022-03-27 09:10:21 nested if else in vb.net
-
VBA 2022-03-27 09:10:09 excel vba string to bits
-
VBA 2022-03-25 02:00:15 vba verticalalignment
-
VBA 2022-03-24 12:20:06 Excel web scraping
-
VBA 2022-03-24 10:11:00 excel vba BitToLong
-
VBA 2022-03-21 18:00:05 excel vba save file txt