查找和替换?

时间:2014-05-02 16:23:18

标签: mailmerge

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

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

重要的是我能够一次编辑多个文档而不是一次能够进行多次编辑。

1 个答案:

答案 0 :(得分:1)

好的,所以我能够为自己的问题创建一个解决方案。为此,我创建了以下代码,以便根据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:\MailMerges\Definitions\Equip.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