Home > Software design >  Replacing string by another string in Word app using VBA
Replacing string by another string in Word app using VBA

Time:03-29

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, i wrote that code but i cant figure why its not working

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

Edit : The word file is launched but the string is not replaced

CodePudding user response:

  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
  • Related