0
votes

My word document template has several local styles that, combined, make a box (boxPara, boxNote, boxTitle, etc). Unfortunately all my boxes are missing the boxTitle paragraphs. My goal is to have a macro that looks for the first boxPara and adds in a blank boxTitle before it - then looks for the boxNote (last item in the box) to reset.

Problem is I'm having difficulty styling the paragraph. The closest I've come is styling the current paragraph wrong, inserting the new paragraph, then re-styling the current paragraph correctly. This seems rather...wrong. And I'd also like to be able to set the text of the inserted paragraph.

Sub addTag()

Dim BoxStart As Integer
Dim Para As Word.Paragraph

BoxStart = 0

For Each Para In ActiveDocument.Paragraphs
    If Para.Format.Style = "BoxParagraph" And BoxStart = 0 Then
        BoxStart = 1
        ' Selection.Paragraphs(1).Range.InsertParagraphBefore

        Para.Format.Style = "BoxTitle"
        Para.Range.InsertParagraph
        Para.Format.Style = "BoxParagraph"

        ' Testing the flag works correctly
        ' Debug.Print BoxStart  
        ' Debug.Print Para.Range.Text
    ElseIf Para.Format.Style = "BoxNote" Then
        BoxStart = 0
        ' Debug.Print BoxStart
    End If

Next

End Sub
1

1 Answers

0
votes

Here is the solution:

Dim BoxStart As Integer
Dim Para As Word.Paragraph

BoxStart = 0

For Each Para In ActiveDocument.Paragraphs
    If Para.Format.Style = "BoxParagraph" And BoxStart = 0 Then
        BoxStart = 1

        ' Insert Box Title with tags before start of answer boxes
        ' Insert paragraph before current paragraph
        Para.Range.InsertParagraphBefore

        ' Select current paragraph
        Para.Range.Select
        ' Move to previous paragraph
        Selection.MoveUp Unit:=wdParagraph, Count:=1
        Selection.MoveEnd Unit:=wdCharacter, Count:=-1

        ' format previous pararaph
        Selection.Paragraphs.Format.Style = "BoxTitle"

        ' Testing the flag works correctly
        ' Debug.Print BoxStart  
        ' Debug.Print Para.Range.Text
    ElseIf Para.Format.Style = "BoxNote" Then
        BoxStart = 0
        ' Debug.Print BoxStart
    End If

Next

End Sub