替换字符串变量 (VBA) 中的多个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36983532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace multiple characters in a string variable (VBA)
提问by yuro
How can I replace more than one thing in a string variable?
如何替换字符串变量中的多个内容?
Here my example function in VBA:
这是我在 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?
有更好的解决方案吗?
回答by Gary's Student
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.
垃圾的每个元素都可以是子字符串或单个字符。
回答by F.Kokert
If it is only about a few characters then I would go with Marco but in VBA:
如果只有几个字符,那么我会选择 Marco 但在 VBA 中:
unitNr = Replace(Replace(unitNr, "OE", ""), ";", "")
回答by Marco Vos
Does it need to be VBA? This formula should also work:
它需要是VBA吗?这个公式也应该有效:
=SUBSTITUTE(SUBSTITUTE("replace","e",""),"a","")
The output wil be 'rplc'
输出将是'rlc'
回答by SnowballsChance
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 commentby 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!
我希望这可以帮助别人。干杯!

