无论字符串中的何处都摆脱空白

时间:2019-01-15 01:29:24

标签: vba

我试图删除空格,而不管它在字符串中处于什么位置。我必须在VBA中编写代码。以下是我到目前为止所写的内容。当我使用chr(32)或space(1)时,VBA似乎适合并且不喜欢我所写的内容。 换句话说,我想将一个字符串传递给cleanFunction: FB 10-0073 并返回: FB100073。注意,没有空格。

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?,-" 'chr(32),chr(95),chr(160),chr(47),chr(45)"  'modify as needed
Private Const EXPC As String = "EXP_C"

Public Function cleanString(ByVal text As String) As String
    Dim newString As String
    Dim char As Variant
    For Each char In Split(SpecialCharacters, ",")
        newString = Trim(Replace(text, char, ""))
    Next
    cleanString = newString
End Function

1 个答案:

答案 0 :(得分:1)

摆脱角色

1.5问题

  • 变量中没有空格字符(可能是错字)。
  • 您总是在初始文本上进行修剪替换,所以 变体中的最后一个字符(在您的情况下为“-”)将被替换,其他字符 不会。

代码

Option Explicit

Function cleanString(ByVal CleanText As String) As String
    Const SpecialCharacters As String = _
            "!,@,#,$,%,^,&,*,(,),{,[,],},?,-,_,/, " ' chr(160)
    Dim newString As String
    Dim char As Variant
    Dim i As Integer
    newString = CleanText
    char = Split(SpecialCharacters, ",")
    For i = 0 To UBound(char)
        newString = Replace(newString, char(i), "")
    Next
    cleanString = newString
End Function