我有一组文档(很多),其中每个文件头中都有一个带有硬编码地址条目的表。我需要更新所有这些文档,用mergefield替换这些硬编码地址。代码在excel电子表格中,用户选择包含要更新的文档的文件夹。下面是进行更新的地方的摘录,例如尝试用{MERGEFIELD Address_Line1}替换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发布于 2019-05-13 00:27:58
涉及表、字段等的Instr不可靠。此外,在您的代码中,Selection.Range指的是一个Excel选择!要引用一个单词选择,您需要wd.Selection.Range。无论如何,没有必要选择任何东西。尝试:
For Each hf In doc.Sections(1).Headers
With hf.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "1 Maple Road"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute
End With
If .Find.Found = True Then
.Fields.Add .Range, wdFieldEmpty, "MERGEFIELD Address_line1", False
End If
End With
Next发布于 2019-05-16 09:50:00
抱歉让事情更清楚了。在文档标题中,有一个带有3个单元格的表(右侧)。第二个on有硬编码地址,例如Maple SomeCity SomePostCode,我需要用mergefield替换这个单元格的内容。
MERGEFIELD Address\_Line1 MERGEFIELD Address\_Line2 MERGEFIELD Address\_City MERGEFIELD Address\_PostCode (只要硬编码条目与指定的公路、城镇、城市和PostCode匹配),这是在excel VBA中完成的批处理工作,每次只针对一个文件夹,其中包含许多要更新的文档。格式也需要保留,谢谢。
https://stackoverflow.com/questions/56100279
复制相似问题