Search code examples
excelvbams-wordoffice-automation

Change the footer in word doc using vba


i have a .docx template with string that i want to replace by another one (like serialNumber, date, author, etc). I want to use excel for that.


    Dim MaFeuille As Worksheet
    Set MaFeuille = Sheets("Information")

    Dim file As String
    file = ActiveWorkbook.Path & "\" & "nomfichier.docx"

    Dim word_app As Object
    Set word_app = CreateObject("Word.Application")
    With word_app
        .Visible = True
        .WindowState = 1 'value for wdWindowStateMaximize
    End With

    Dim word_fichier As Object
    
    Set word_fichier = word_app.Documents.Open(file)
    With word_fichier.Range.Find
        .Text = "blabla"
        .Replacement.Text = "coucou"
        .Execute Replace:=2
    End With

It's working but not in the header/footer. So i red the documentation about Header/Footer (https://learn.microsoft.com/fr-fr/office/vba/api/word.headersfooters), so just for trying i typed the exemple :

    With word_fichier.Sections(1)
        .Headers(wdHeaderFooterPrimary).Range.Text = "Header goes here"
        .Footers(wdHeaderFooterPrimary).Range.Text = "Footer goes here"
    End With

But i have a 5941 error.


Solution

  • Thanks to @Míša Charvátová, i added "Microsoft Word 16.0 Object Library" and it's working.

    Edit (better answer) :

    Do you have "Microsoft Word 16.0 Object Library" added to References under tools? I tried your code and when this was added, it worked