简体   繁体   English

使用 Excel VBA 替换 Word 文档中的字符串

[英]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.我有一个 .docx 模板,其中包含要使用 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. Word 文件已启动,但未替换字符串。

  1. Always declare all your variables, insert Option Explicit at the top of your module to help you enforce this.始终声明所有变量,在模块顶部插入Option Explicit以帮助您执行此操作。

  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).您在Find对象中缺少.Execute ,您还需要指定Replace参数来执行替换(而不仅仅是查找)。

  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.如果您是后期绑定,那么您不能使用 Word 库中存在的枚举,例如wdWindowStateMaximize而不手动定义它,因此替代方法是直接提供值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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