user6096423
user6096423

Reputation: 141

Word Macro Shuts Down exactly half way through Document

My first challenge was to automate underlining headers in a word doc. This code worked:

Sub Underline_Header()

Dim numOfParagraphs As Integer
numOfParagraphs = ActiveDocument.BuiltInDocumentProperties("NUMBER OF PARAGRAPHS")
Selection.HomeKey Unit:=wdStory
For x1 = 1 To numOfParagraphs

Selection.Paragraphs(1).Range.Select

char_count = Len(Selection.Paragraphs(1).Range)

If char_count < 50 Then
Selection.Font.Underline = True
End If

Selection.MoveDown Unit:=wdParagraph, Count:=1

Next x1


End Sub

But it turns out if the doc is 20 pages, the macro stops at page 10. If 10, stops at 5. 4, then stops at page 2.

I have tried altering the code at Unit:=wdStory to Unit:=wdDocument but that was not the solution. I also tried adding Selection.EndKey Unit:=wdStory to the code but I get the same result.

Upvotes: 0

Views: 46

Answers (1)

Slai
Slai

Reputation: 22876

You can simplify it to something like

Sub Underline_Headers()
    Dim p As Paragraph
    For Each p in ActiveDocument.Paragraphs
        If Len(p.Range.Text) < 50 Then
            p.Range.Font.Underline = True
        End If
    Next p
End Sub

Upvotes: 2

Related Questions