Count specific characters in a cell - Excel

后端 未结 4 1578
日久生厌
日久生厌 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条回答
  •  旧巷少年郎
    2021-02-11 04:38

    Here is a simple version I created:

    Function CountSpecialCharacters(rng As Range) As String
        Dim regEx As New RegExp, matches As MatchCollection
    
        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = "[^a-zA-Z0-9]" '~~~> this counts any character not a to z or a number
        End With
    
        Set matches = regEx.Execute(rng)
    
        CountSpecialCharacters = matches.Count
    End Function
    

    Two points:

    1. In the VBA editor you need to set References > Microsoft VBScript Regular Expressions 5.5
    2. You call the function on your spreadsheet e.g. =CountSpecialCharacters(A2)

提交回复
热议问题