简体   繁体   中英

Replacing string in Word document using Excel VBA

I have a .docx template with a string I want to replace (like serialNumber, date, author, etc.) using Excel VBA.

Private Sub Create()

    Dim MaFeuille As Worksheet
    Dim file As String

    Set MaFeuille = Sheets("Information")

    file = ActiveWorkbook.Path & "\" & "nomfichier.docx"
    
    Set word_app = CreateObject("Word.Application")
    With word_app
        .Visible = True
        .WindowState = wdWindowStateMaximize
    End With

    Set word_fichier = word_app.documents.Open(file)
    word_app.Selection.Find.ClearFormatting
    word_app.Selection.Find.Replacement.ClearFormatting
            
    With word_app.Selection.Find
        .Text = "blabla"
        .Replacement.Text = "coucou"
    End With
        
End Sub

The Word file is launched but the string is not replaced.

  1. Always declare all your variables, insert Option Explicit at the top of your module to help you enforce this.

  2. You are missing .Execute in the Find object, you also need to specify the Replace argument to perform the replace (instead of just find).

  3. If you are late-binding, then you can't use enumeration that exist in Word library such as wdWindowStateMaximize without defining it manually so the alternative is to provide the value directly instead.

Option Explicit

Private Sub Create()

    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 'value for wdReplaceAll
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM