VBA Word宏未按预期工作,文档中有字段结果

VBA Word宏未按预期工作,文档中有字段结果,vba,ms-word,textfield,Vba,Ms Word,Textfield,我有一个word文档(报告),在该文档中,我导入了许多文本文件,其中的字段如下: {INCLUDETEXT "C:\\PATH\\TOXMLFILES\\Request.xml" \*CHARFORMAT} 同时,我在打开文档时用宏更新所有这些字段 Sub AutoOpen() With Options .UpdateFieldsAtPrint = True .UpdateLinksAtPrint = True End With ActiveDocument.Fields.Up

我有一个word文档(报告),在该文档中,我导入了许多文本文件,其中的字段如下:

{INCLUDETEXT "C:\\PATH\\TOXMLFILES\\Request.xml" \*CHARFORMAT}
同时,我在打开文档时用宏更新所有这些字段

Sub AutoOpen()
With Options
    .UpdateFieldsAtPrint = True
    .UpdateLinksAtPrint = True
End With
ActiveDocument.Fields.Update
End Sub
现在我需要突出显示
标记之间导入的XML的文本(在
IncludeText
字段中)

下面是我在stackoverflow上获得的代码,用于突出显示文本(使其加粗)

Sub-boldbetweenkotes()
'引用查找宏的基
将增益设置为布尔值
Dim blnFindStart为布尔值
Dim BlnIndended为布尔值
Dim rngFind作为单词范围
Dim rngFindStart作为字范围
Dim rngFindEnd作为字范围
设置rngFind=ActiveDocument.content
设置rngFindStart=rngFind.Duplicate
做
'设置第一个报价对的查找
使用rngFindStart.Find
.ClearFormatting
.Text=“”
.Replacement.Text=“”
.Forward=True
.wrap=wdFindStop
blnFindStart=.Execute
以
如果blnFindStart,则
rngFindStart。折叠wdCollapseEnd
设置rngFindEnd=rngFindStart.Duplicate
rngfind.Find.Text=“”
blnfinded=rngfind.Find.Execute
如果被发现的话
rngFindStart.End=rngFindEnd.Start
“大胆点
rngFindStart.Font.Bold=True
rngFindStart.Start=rngFindEnd.End
rngFindStart.End=rngFind.End
BLN增益=真
其他的
blnSearchAgain=False
如果结束
其他的
blnSearchAgain=False
如果结束
BLNSEARCHANGE=True时循环
端接头
问题是,当我在Word文档中运行宏(带有
IncludeText
字段)时,它会在faultstring标记之间循环并加粗第一次出现的文本。当我在一个新的Word文档中使用一些随机文本和faultrstring标记运行它时,它工作得很好


编辑:原来问题是由于
IncludeText
字段中存在faultstring标记。打开文档并更新字段后,我需要将字段转换为静态文本。如何才能做到这一点?

要使用Word的对象模型(如VBA)将动态字段内容转换为静态文本,需要使用
字段。取消链接
方法。对于整个文件:

ActiveDocument.Fields.Unlink
这也适用于任何给定的
范围
;要删除最后一段中的字段,例如:

ActiveDocument.Paragraphs.Last.Range.Fields.Unlink
要仅取消某一类型字段的链接,请循环
字段
集合,测试
字段。键入
并相应取消链接。例如,对于IncludeText:

Sub DeleteIncludeTextFields()
    Dim doc As word.Document

    Set doc = ActiveDocument
    Debug.Print DeleteFieldType(wdFieldIncludeText, doc)
End Sub

Function DeleteFieldType(fldType As word.WdFieldType, doc As word.Document) _
         As Long

    Dim fld As word.Field
    Dim counter As Long

    counter = 0
    For Each fld In doc.Fields
        If fld.Type = wdFieldIncludeText Then
            fld.Unlink
            counter = counter + 1
        End If
    Next

    DeleteFieldType = counter
End Function
假设要在更新文档后对文档中的所有字段执行此操作:

Sub AutoOpen()
  With Options
    .UpdateFieldsAtPrint = True
    .UpdateLinksAtPrint = True
  End With
  ActiveDocument.Fields.Update
  ActiveDocument.Fields.Unlink
End Sub

如果不取消INCLUDETEXT字段的链接,则标记之间的任何格式都将立即丢失,因为任何原因都会刷新这些字段。相反,如果取消INCLUDETEXT字段的链接,它们将不再更新以反映基础数据中的更改。因此,也许最好的方法是锁定字段,而不是取消链接,这样就可以只根据需要解锁和刷新字段。非常感谢,您帮了我很多;)
Sub AutoOpen()
  With Options
    .UpdateFieldsAtPrint = True
    .UpdateLinksAtPrint = True
  End With
  ActiveDocument.Fields.Update
  ActiveDocument.Fields.Unlink
End Sub