将代码更改为“删除”而不是“允许”字符

时间:2015-08-24 22:15:22

标签: excel-vba udf vba excel

列出的字符函数allows(在本例中)

Case 48 To 57, 65 To 90, 97 To 122:

是否可以将此更改为Remove列出的字符?

由于

Function AlphaNumericOnly(strSource As String) As String
    Dim i As Integer
    Dim strResult As String

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 48 To 57, 65 To 90, 97 To 122:
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next
    AlphaNumericOnly = strResult
End Function

1 个答案:

答案 0 :(得分:1)

如果您打算使用For ... Next - 只需添加Case Else

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 48 To 57, 65 To 90, 97 To 122:
            Case Else:
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next

正如@pnuts指出并且@brettdj answered - RegEx效率更高,在你的情况下,函数可能如下:

Function NonAlphaNumericOnly(strSource As String) As String
    With CreateObject("VBScript.RegExp")
        .Global = True
        .IgnoreCase = True
        .Pattern = "[\w]+"
        NonAlphaNumericOnly = .Replace(strSource, "")
    End With
End Function