Count specific characters in a cell - Excel

后端 未结 4 1579
日久生厌
日久生厌 2021-02-11 03:43

I would like to count all special characters (!%_*?+-,) in a cell.

For example:

With this formula =LEN(D2)-LEN(SUBSTITUTE(D2;\"!\";\"\")) i

4条回答
  •  梦毁少年i
    2021-02-11 04:29

    You can do this with a simple array formula:

    =SUM(LEN(A2) - LEN(SUBSTITUTE(A2,Special_Characters,"")))
    

    Special_Characters is a range listing all your special characters. You could manually enter them as an array constant if you prefer:

    =SUM(LEN(A2) - LEN(SUBSTITUTE(A2,{"%";"_";"*";"?";"+";"-";",";"!"},"")))   
    

    but the named range seems simpler.


    To array-enter a formula, after entering the formula into the cell or formula bar, hold down ctrl + shift while hitting enter. If you did this correctly, Excel will place braces {...} around the formula.

    If you prefer a VBA solution, I would suggest the code below. You will need to modify .Pattern to include any other characters you do NOT want to count. In the code below, any character that is not an upper or lower case letter, or a digit, will be counted as a special character.

    Option Explicit
    Function SpecialChars(S As String) As Long
        Dim RE As Object
    Set RE = CreateObject("vbscript.regexp")
    With RE
        .Global = True
        .Pattern = "[^A-Za-z0-9]"
        SpecialChars = Len(S) - Len(.Replace(S, ""))
    End With
    End Function
    

提交回复
热议问题