I requested help from the forum about 6 months ago but my issue remains only partly resolved. I'm hoping someone may help me recognize where my mistake is taking place in the code I have created.
My issue is that I want to use VBA to insert a very brief amount of standardized text before the English-language string in my multilevel list headings. These headings exist as Styles within my ~600 page document.
For instance, I have: 1.1.1 The Quick Brown Fox.
What I want is: 1.1.1 (XXxx) The Quick Brown Fox.
I created this macro which I then customized for each of the 6 heading levels in my document.
Public Sub InsertFOUOH1()
'Inserts U//FOUO before all first order Headings)
'Macro works on whole document
Dim doc As Document
Dim para As Paragraph
Const MyText = "(U//FOUO) "
Application.ScreenUpdating = False
Set doc = ActiveDocument
For Each para In doc.Paragraphs
If para.Style = doc.Styles(wdStyleHeading1) Then
para.Range.InsertBefore (MyText)
End If
Next para
End Sub
This code is flawed/broken but I cannot find a solution. This works on Heading Levels 1-3. It fails on Heading Levels 4-6. The document is long and my assumption is that the sheer quantity of level 4 headings and greater causes the flawed code to fail. The code simply never completes at these heading levels.
This seems to be the part of the code that is incorrect:
For Each para In doc.Paragraphs
If para.Style = doc.Styles(wdStyleHeading1) Then
para.Range.InsertBefore (MyText)
I've tried dozens of variations on my macro and they all seem to fail at this point. In debugging, the debugger simply jumps right over the "If / Then" lines. They never get highlighted in yellow when debugging.
My understanding is that you can't programmatically select a paragraph in VBA. My heading levels are paragraphs to Word. So, my line "para.Range.InsertBefore (Mytext)" may not make any sense to the code. I tried creating a Range to make the macro work (Ranges have a 'Selection' property) but I'm doing something wrong.
I would certainly appreciate any advice about correcting my code.