JeroenDV
JeroenDV

Reputation: 135

Changing default Styles in a Word document in a separate sub using Excel

In a word document controlled by Excel I want to make a subtle change to the used default styles. This works using the following code, when a word document is already open:

Private Sub basic_syle()
    Dim objWord As Word.Application
    Dim objSelection As Word.selection

    Set objWord = GetObject(, "Word.application")
    Set objSelection = objWord.selection

    adjust_obj_style
End Sub

Sub adjust_obj_style()
    ActiveDocument.Styles("Heading 1").ParagraphFormat.PageBreakBefore = False
End Sub

However if I want to let Excel create the word document and adjust the style the style is not changed.

Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim objSelection As Word.selection

Private Sub basic_syle()
    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Add
    Set objSelection = objWord.selection

    objWord.Visible = True

    adjust_obj_style
End Sub

While I think it has to do with the activeDocument class I did not yet find a correct solution. Activating the document object was no solution.

Styles documentation PageBreak documentation

Upvotes: 0

Views: 43

Answers (1)

braX
braX

Reputation: 11735

You need to redefine the sub:

Sub adjust_obj_style(doc as Object)

and then pass that document to the sub:

adjust_obj_style objDoc

and then use that variable instead of ActiveDocument like this:

doc.Styles("Heading 1").ParagraphFormat.PageBreakBefore = False

Upvotes: 1

Related Questions