Word文档-用合并字段替换标题表中的文本

时间:2019-05-12 14:38:57

标签: excel vba ms-word mergefield

我有一组文档(批次),每个文档的标题中的表头中都有一个带有硬编码的地址条目的表。我需要更新所有这些文档,以将这些硬编码的地址替换为mergefields。 该代码位于excel电子表格中,用户可以在其中选择包含要更新文档的文件夹。以下摘录了完成更新的位置,例如尝试用{MERGEFIELD Address_Line1}替换Maple Road 1的硬编码值。不知道我要去哪里错,但消息通常是错误的参数数量或根本不起作用 谢谢

    Dim doc As Word.Document
Dim hf As Word.HeaderFooter
Dim lr As ListRow
Dim updated As Boolean
Dim tableCount As Integer
Dim t As Integer
Dim c As Cell

Set wd = New Word.Application
Set doc = wd.Documents.Open(Filename:="c:/......./example.docx", ReadOnly:=False)


For Each hf In doc.Sections(1).Headers()

    tableCount = hf.Range.Tables.Count
    For t = 1 To tableCount
        For Each c In hf.Range.Tables(t).Range.Cells
            If InStr(1, c.Range.Text, "1 Maple Road") > 0 Then
                c.Range.Text = ""
                c.Range.Select
                doc.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=True, Text:="MERGEFIELD Address_line1"
            End If
        Next c
    Next t
Next hf


doc.Close False
wd.Quit False

还是尝试过

Dim doc As Word.Document
Dim hf As Word.HeaderFooter
Dim lr As ListRow
Dim updated As Boolean
Dim tableCount As Integer
Dim t As Integer
Dim c As Cell

Set wd = New Word.Application
Set doc = wd.Documents.Open(Filename:="c:/......./example.docx", ReadOnly:=False)


For Each hf In doc.Sections(1).Headers()

    tableCount = hf.Range.Tables.Count
    For t = 1 To tableCount
        For Each c In hf.Range.Tables(t).Range.Cells
            If InStr(1, c.Range.Text, "1 Maple Road") > 0 Then
                c.Range.Text = ""
                c.Range.Select
                Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=True
                Selection.TypeText Text:="MERGEFIELD Address_Line1"
            End If
        Next c
    Next t
Next hf


doc.Close False
wd.Quit False

2 个答案:

答案 0 :(得分:0)

在涉及表,字段等的地方,Instr不可靠。此外,在您的代码中,Selection.Range指的是 Excel 选择!要引用单词选择,您需要wd.Selection.Range。无论如何,都无需选择任何内容。试试:

Rigidbody

答案 1 :(得分:0)

道歉让事情变得更加清晰。在文档标题中,有一个包含3个单元格的表(在右侧)。第二个有硬编码的地址,例如 枫树道1号 某镇 SomeCity SomePostCode 我需要用mergefields替换此单元格的内容,例如
    MERGEFIELD Address_Line1
    MERGEFIELD Address_Line2
    MERGEFIELD地址_城市MERGEFIELD地址_邮政编码
(只要硬编码的条目与指定的道路,城镇,城市和邮政编码匹配) 这是在excel VBA中完成的批处理作业,一次定位到一个文件夹,其中包含许多要更新的文档。 格式也需要保留 谢谢

相关问题