Macro to count characters with specific formatting

E

ex_ef_ex

Hi all,

I am not a programmer and have zero training in VBA, so bear with me.

I would like to create a macro that would allow a user to:

a) count the highlighted characters (without spaces) in a selection (this selection would be made by the user before the macro is run)

b) count the highlighted characters (without spaces) in the whole document

c) present the results in a message box.

So far, after spending a few hours googling for code, I have come up with the following macro - which of course does not work.


=======================
Sub HighlightCount()

Dim SelectionChar As Range
Dim TotalChar As Range

Set SelectionChar = Selection.Range

Do
With SelectionChar.find
.Highlight = True
.Forward = True
.Wrap = wdFindStop
.Execute
End With

If SelectionChar.find.Found = True Then
SelectionCharCount = SelectionCharCount + SelectionChar.ComputeStatistics(wdStatisticCharacters)
Else
Exit Do
End If
Loop

Set TotalChar = ActiveDocument.Content

Do
With TotalChar.find
.Highlight = True
.Forward = True
.Wrap = wdFindStop
.Execute
End With

If TotalChar.find.Found = True Then
TotalCharCount = TotalCharCount + TotalChar.ComputeStatistics(wdStatisticCharacters)
Else
Exit Do
End If
Loop


MsgBox "There are " & SelectionCharCount & " highlighted characters in the selection and " & TotalCharCount & " highlighted characters in the whole document"
End Sub


=======================

Counting the highlighted characters in the whole documents seems to work, but counting just the ones in the selection does not.

Any input on how to correct this would be greatly welcome.

Thanks in advance,

ex_ef_ex
 

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