I would like to count all special characters (!%_*?+-,) in a cell.
For example:
With this formula =LEN(D2)-LEN(SUBSTITUTE(D2;\"!\";\"\"))
i
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
=8*LEN(D2)-LEN(SUBSTITUTE(D2;"!";""))-LEN(SUBSTITUTE(D2;"%";""))-LEN(SUBSTITUTE(D2;"_";""))-LEN(SUBSTITUTE(D2;"*";"")) -LEN(SUBSTITUTE(D2;"?";""))-LEN(SUBSTITUTE(D2;"+";""))-LEN(SUBSTITUTE(D2;"-";""))-LEN(SUBSTITUTE(D2;",";""))
Using formulas only, not VBA, this is possible with the following two approaches:
Consider the text in A1
:
First approach:
Multiple nested SUBSTITUTE
:
=LEN(A1)-LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,",",""),"-",""),"+",""),"?",""),"*",""),"_",""),"%",""),"!",""))
Second approach:
Using SUMPRDUKT
for getting the MID
function in array context to get each single charachter of the string in A1
compared with each single special character:
=SUMPRODUCT(--(MID(A1,ROW($1:$1000),1)={"!","%","_","*","?","+","-",","}))
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:
References > Microsoft VBScript Regular Expressions 5.5
=CountSpecialCharacters(A2)