问题
How can I replace more than one thing in a string variable?
Here my example function in vba:
Private Function ExampleFunc(ByVal unitNr$) As String
If InStr(unitNr, "OE") > 0 Then
unitNr = Replace(unitNr, "OE", "")
unitNr = Replace(unitNr, ";", "")
End If
...
End Function
Is there a better solution?
回答1:
You could use an array and loop over its elements:
Sub MAIN()
Dim s As String
s = "123456qwerty"
junk = Array("q", "w", "e", "r", "t", "y")
For Each a In junk
s = Replace(s, a, "")
Next a
MsgBox s
End Sub
Each element of junk can be either a sub-string or a single character.
回答2:
Does it need to be VBA? This formula should also work:
=SUBSTITUTE(SUBSTITUTE("replace","e",""),"a","")
The output wil be 'rplc'
回答3:
I found this post quite helpful so I thought I would share how I was able to use it to my advantage. Combining the accepted answer from "Gary's Student" with this comment by Charles Williams, I came up with a slick way to remove non numeric characters from any given string.
Public Function RemoveNonNumChars(s As String) As String
Dim bytes() As Byte
Dim char As String
bytes = StrConv(s, vbFromUnicode)
For Each c In bytes
char = chr(c)
If Not IsNumeric(char) Then
'remove character from array
s = Replace(s, char, "")
Debug.Print "Removing " & char & " from string." & Chr(13) s
End If
Next c
End Function
I hope this helps someone. Cheers!
回答4:
If it is only about a few characters then I would go with Marco but in VBA:
unitNr = Replace(Replace(unitNr, "OE", ""), ";", "")
来源:https://stackoverflow.com/questions/36983532/replace-multiple-characters-in-a-string-variable-vba