我有一个word文档(报告),并且在该文档中,我正在导入具有以下字段的许多文本文件:
{INCLUDETEXT "C:\\PATH\\TOXMLFILES\\Request.xml" \*CHARFORMAT}
我也在打开文档时使用宏更新所有这些字段...
Sub AutoOpen()
With Options
.UpdateFieldsAtPrint = True
.UpdateLinksAtPrint = True
End With
ActiveDocument.Fields.Update
End Sub
现在,我需要IncludeText
在<faultstring></faultstring>
标签之间突出显示那些导入的XML的文本(在字段中)
这是我在stackoverflow上获得的用于突出显示文本的代码(使其变为粗体)
Sub BoldBetweenQuotes()
' base for a quotes finding macro
Dim blnSearchAgain As Boolean
Dim blnFindStart As Boolean
Dim blnFindEnd As Boolean
Dim rngFind As word.Range
Dim rngFindStart As word.Range
Dim rngFindEnd As word.Range
Set rngFind = ActiveDocument.content
Set rngFindStart = rngFind.Duplicate
Do
' set up find of first of quote pair
With rngFindStart.Find
.ClearFormatting
.Text = "<faultstring>"
.Replacement.Text = ""
.Forward = True
.wrap = wdFindStop
blnFindStart = .Execute
End With
If blnFindStart Then
rngFindStart.Collapse wdCollapseEnd
Set rngFindEnd = rngFindStart.Duplicate
rngFindEnd.Find.Text = "</faultstring>"
blnFindEnd = rngFindEnd.Find.Execute
If blnFindEnd Then
rngFindStart.End = rngFindEnd.Start
' make it bold
rngFindStart.Font.Bold = True
rngFindStart.Start = rngFindEnd.End
rngFindStart.End = rngFind.End
blnSearchAgain = True
Else
blnSearchAgain = False
End If
Else
blnSearchAgain = False
End If
Loop While blnSearchAgain = True
End Sub
问题是,当我在Word文档(带有IncludeText
字段)中运行宏时,它会不断循环并以粗体显示故障字符串标记之间的文本的第一出现。当我在带有一些随机文本和faultrstring标签的新Word文档中运行它时,效果很好...
编辑:原来的问题是由于在IncludeText
字段内的faultstring标签。打开文档并更新字段后,我需要将字段转换为静态文本。我怎样才能做到这一点?
为了使用Word的对象模型(例如VBA)将动态字段内容转换为静态文本,需要使用该Fields.Unlink
方法。对于整个文档:
ActiveDocument.Fields.Unlink
对于任何给定Range
,这也是可能的;删除最后一段中的字段,例如:
ActiveDocument.Paragraphs.Last.Range.Fields.Unlink
为了仅取消链接某种类型的字段,请循环Fields
收集,测试Field.Type
并相应地取消链接。例如,对于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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句