查找和替换



有人知道更复杂的查找和替换方法吗?例如,我有许多带有合并字段的文档。我需要能够根据定义翻译列表更改这些文档中的合并字段。在这个例子中,假设我在M$ word中创建了100个设备租赁,保存为。dot。下面的每个合并字段都存在,我想一次将它们全部更改为一个新值,如下所示。

{MERGEFIELD state} -> {MERGEFIELD ownerstate}
{MERGEFIELD city} -> {MERGEFIELD ownercity}
{MERGEFIELD zip} -> {MERGEFIELD ownerzip}

我能够一次编辑多个文档并不重要,重要的是我能够一次编辑多个文档。

好的,所以我能够为我自己的问题创建一个解决方案。为此,我创建了以下代码,根据excel中的定义列表进行查找和替换。

Option Explicit
Private MyXL As Object
Sub Test()
Dim WB As Excel.Workbook, WS As Excel.Worksheet, MyDefTbl As Excel.Range, MyRow As Excel.Range
Dim MySearchRng As Excel.Range, ReplacementRng As Excel.Range
Dim myDoc As Document
Call MyInitializeOfficeApps
'Define the Workbook that contains the Definitions
Set WB = MyXL.Workbooks.Open("E:MailMergesDefinitionsEquip.xlsx")
'Define the Woksheet that contains the Definition list
Set WS = WB.Worksheets("Sheet1")
'Define the Range name that defines the Definition list
Set MyDefTbl = WS.Range("MyDefs")
'Define the Document to be changed
Set myDoc = ActiveDocument
For Each MyRow In MyDefTbl.Rows
    Set MySearchRng = WS.Cells(MyRow.Row, 1)
    Set ReplacementRng = WS.Cells(MyRow.Row, 2)
    'MsgBox MySearchRng & "====>" & ReplacementRng
    myDoc.Select
    With Selection.Find
        .Text = " MERGEFIELD " & MySearchRng.Text
        .Replacement.Text = " MERGEFIELD " & ReplacementRng.Text
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
Next MyRow
Set MyDefTbl = Nothing
Set MyRow = Nothing
Set WS = Nothing
Set WB = Nothing
Set MyXL = Nothing
Set myDoc = Nothing
MsgBox "Complete"
End Sub

Sub MyInitializeOfficeApps()
On Error Resume Next
Set MyXL = GetObject(, "Excel.Application")
If MyXL Is Nothing Then
    Set MyXL = CreateObject("Excel.Application")
End If
On Error GoTo 0
MyXL.Visible = True
End Sub

相关内容

  • 没有找到相关文章

最新更新