PDA

View Full Version : [SOLVED:] Struggling to get Heading 1 Ranges



Paul_Hossler
07-30-2020, 09:10 AM
I have a document with multiple sections (doesn't matter) with Heading 1 paragraphs, and I'm trying to get each Heading 1 'chunk' into a range so that I can do statistics, etc. on just that piece

Example document structure:

DocStart
text

H1 #1
text

H1 #2
text

H1 #3
text
DocEnd

So I'm trying to get a loop that returns 4 Ranges:

DocStart to just before H1 #1 (first char at top to last char before the H1 paragraph)
H1 #1 to just before H1 #2
H1 #2 to just before H1 #3
H1 #3 to DocEnd

Can someone get me started please?

Edit#2 - This is what I have so far. Seems to work, but not sure if it'll stand the test of time. Word's object model is pretty much a mystery to me, so I'm open to any suggestions




Option Explicit


Sub ChunkHeading1()
Dim rChunk As Range
Dim n As Long

Selection.HomeKey Unit:=wdStory

Set rChunk = Selection.Range

With Selection.Find
.ClearFormatting
.Style = ActiveDocument.Styles("Heading 1")


.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False

Do While .Execute

'remember end position = before the start of the Heading 1 paragraph
Selection.MoveLeft Unit:=wdCharacter, Count:=2

rChunk.End = Selection.End

n = n + 1
MsgBox "Chunk # " & n & " -- " & rChunk.ComputeStatistics(wdStatisticWords)

rChunk.Move Unit:=wdParagraph, Count:=2
rChunk.Select

Loop

'from the last Heading 1 to end of doc
Selection.EndKey Unit:=wdStory, Extend:=wdExtend
n = n + 1
MsgBox "Chunk # " & n & " -- " & Selection.Range.ComputeStatistics(wdStatisticWords)

End With


End Sub

macropod
07-30-2020, 05:36 PM
See: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_windows8-mso_archive/macro-to-compute-headings-word-counts/8bba18a7-e931-41d7-9481-1bcff364dd3a?auth=1

Paul_Hossler
07-30-2020, 06:20 PM
See: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_windows8-mso_archive/macro-to-compute-headings-word-counts/8bba18a7-e931-41d7-9481-1bcff364dd3a?auth=1

That's great

Thanks

Works well, but sometimes there's text before the first Heading 1

26939

Is there a way to make it work to show the word count for such text also?

My long range project is to take each such ranges (which only are used to display word counts right now) and do some other statistics and maybe some processing on the range

Thanks

macropod
08-02-2020, 05:04 PM
There are numerous ways of addressing this. For example, have the macro test whether the first:
• Heading1 match is at the start of the document and, if not, capture the preceding text; and
• paragraph is in the Heading1 Style and, if not, temporarily insert one there before running the rest of the code.