Find and replace multiple words in Word

随声附和 提交于 2019-12-25 01:18:44

问题


I really hope you guys can help, I feel like I've been struggling with what should be (and probably is) a really simple problem. I've written an app which creates a folder structure, copies in the relevant test documents based on user inputs, and populates the document header and test sheets with various variables. I have populated the template test documents with placeholders, ("replCustNo","replPrjNo","replCustRef" etc), some in the header, some in the body of the document. I can only seem to replace one word at a time, I can't find a way of listing all the references to find, then listing all the replacement variables. Seems like a very clumsy way of coding to have the find/replace over and over, or call on a sub for it.

Forgive me if this is really basic, I'm very new to coding, I'd really appreciate some help! I'm using vb and office 365

 Dim objWordApp As New Word.Application
    'Open an existing document.  
    Dim objDoc As Word.Document = objWordApp.Documents.Open(projFolder & "SAT\2 HV Tests\Flash.doc")

    objWordApp.ActiveDocument.Sections(1).Headers(1).Range.Select()
    objWordApp.Selection.WholeStory()
    With objWordApp.Selection.Find
        .Text = "replPrjNo"
        .Replacement.Text = RefNo
        .Forward = True
    End With
    objWordApp.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)

    'Save and close the document  
    objDoc.Save()
    objDoc.Close()
    objDoc = Nothing
    objWordApp.Quit()
    objWordApp = Nothing

回答1:


One solution can be with document variables. Select a placeholder in the template document and then Insert tab > Quick Parts > Field... > DocVariable > New name: replPrjNo

Then in the code:

objDoc.Variables("replPrjNo").Value = RefNo
objDoc.Fields.Update

Other solutions can be bookmarks, custom document properties, Mail Merge, or some of the controls in the Developer tab.



来源:https://stackoverflow.com/questions/37752379/find-and-replace-multiple-words-in-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!