Skip to content

Instantly share code, notes, and snippets.

@FedericoTartarini
Created March 8, 2023 07:06
Show Gist options
  • Save FedericoTartarini/dd654cefcce2ecb70f8d986e7b26e2ec to your computer and use it in GitHub Desktop.
Save FedericoTartarini/dd654cefcce2ecb70f8d986e7b26e2ec to your computer and use it in GitHub Desktop.
Macro to count words in each heading in Microsoft Word
Sub CountHeadingSpanText()
Application.ScreenUpdating = False
Dim RngHd As Range, h As Long, strOut As String
' h = CLng(InputBox("Input the Heading level (e.g. 1) for the heading spans to count", "Heading Span Word Counter", 1))
' If (h < 1) Or (h > 9) Then Exit Sub
h = 1
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Style = "Heading " & h
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found
Set RngHd = .Paragraphs(1).Range
Set RngHd = RngHd.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
With RngHd
strOut = strOut & .ComputeStatistics(wdStatisticWords) - .Paragraphs.First.Range.ComputeStatistics(wdStatisticWords) & vbTab & .Paragraphs.First.Range.Text
End With
.Start = RngHd.End
.Find.Execute
Loop
End With
Set RngHd = Nothing
MsgBox "The following word counts are associated with each level " & h & " heading:" & vbCr & strOut
Application.ScreenUpdating = True
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment