Letter counter -- count # of characters in string while ignoring spaces?

  • Thread starter StargateFanFromWork
  • Start date
S

StargateFanFromWork

Is it possible to do something like this in Word, by any chance? I can't
imagine myself how, but then I'm no expert at all. Was hoping to know one
way or another.

TIA. :eek:D
 
G

Greg Maxey

This counts all characters accept spaces:

Sub CharacterCheck()
Dim myString As String
myString = Selection.Range
check_ATOz myString
End Sub
Sub check_ATOz(myString As String)
Dim oCharNum As Long
Dim i As Long
Dim j As Long
For i = 1 To Len(myString)
oCharNum = Asc(Mid(myString, i, 1))
If oCharNum <> 32 Then j = j + 1
Next i
MsgBox "There are " & j & " characters in the selected string."
End Sub
 
J

Jay Freedman

Select the text in question, and click Tools > Word Count. It'll give
you character counts both with and without spaces, among other things.

If you want this for a string variable in code, do this:

Sub Demo()
Dim originalString As String
Dim charCountNoSpace As Long

originalString = Selection.Text
charCountNoSpace = Len(Replace(originalString, " ", ""))

MsgBox originalString & vbCr & _
"With spaces: " & Len(originalString) & _
vbCr & "Without spaces: " & charCountNoSpace
End Sub

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 
S

StargateFan

Select the text in question, and click Tools > Word Count. It'll give
you character counts both with and without spaces, among other things.

If you want this for a string variable in code, do this:

Sub Demo()
Dim originalString As String
Dim charCountNoSpace As Long

originalString = Selection.Text
charCountNoSpace = Len(Replace(originalString, " ", ""))

MsgBox originalString & vbCr & _
"With spaces: " & Len(originalString) & _
vbCr & "Without spaces: " & charCountNoSpace
End Sub

Oh, excellent! Thanks everyone for your replies.

I've never needed the word count in Word so I'd never used it so
didn't realize it would also do letter count. Very good to know. <g>
 
M

macropod

Hi Jay,

Since Len(originalString) and Len(Replace(originalString, " ", "")) will both return 1 if no text is selected, I'd suggest:

Sub NonSpaceStrLen()
Dim a As String, b As Long, c As Long
a = ""
b = 0
c = 0
a = Selection.Range.Text
If a <> "" Then
b = Len(a)
c = Len(Replace(a, " ", ""))
End If
MsgBox "The string has " & b & " character(s), including" & vbCrLf _
& "spaces, and " & c & " non-space character(s)."
End Sub

Cheers
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top