用合并字段替换给定范围的文本

时间:2016-01-06 16:24:11

标签: vba ms-word word-vba

我正在创建一个VBA宏,用于在Word文档中查找<>个标记之间的单词,并将它们转换为合并字段。

这是我提出的第一个脚本

Sub lookForFields()
    '
    ' lookForFields Macro
    '
    Dim para As Paragraph
    Dim lineText As String
    Dim regEx As New RegExp
    Dim strPattern As String: strPattern = "\<(.*?)\>"
    Dim strInput As String
    Dim region As Word.Range
    Dim allmatches As MatchCollection
    Dim currentWord As String

    Debug.Print (vbCrLf + "------------------")
    Dim res As String
    With regEx
        .Global = True
        .MultiLine = False
        .IgnoreCase = True
        .Pattern = strPattern
    End With
    For Each para In ActiveDocument.Paragraphs
        txt = para.Range.Text
        Set allmatches = regEx.Execute(txt)
        For Each m In allmatches
            Set rng = ActiveDocument.Range(Start:=m.FirstIndex + para.Range.Start, End:=m.FirstIndex + Len(m.Value) + para.Range.Start)
            'Set myField = ActiveDocument.Fields.Add(Range:=rng, Type:=wdFieldMergeField, Text:=m.Value)
            rng.HighlightColorIndex = wdYellow
        Next m
    Next para
End Sub

以下说明正确地突出了我想转换的字词:

rng.HighlightColorIndex = wdYellow

但是,如果我取消注释

Set myField = ActiveDocument.Fields.Add(Range:=rng, Type:=wdFieldMergeField, Text:=m.Value)

如果段落中有多个字段,则不会创建合并字段。 创建的合并字段也不知何故似乎&#34;有效&#34;因为右键单击它们来编辑它们的属性会将它们替换为&#34; unknow开关&#34;错误。 我应该怎么做这个?

1 个答案:

答案 0 :(得分:1)

如果使用Alt-F9查看文档中实际发生的情况,您可能会看到每个段落中的第二个和后续字段都插入到代码插入的第一个字段中。

这是因为字段插入会更改文档范围内的字符数。什么都不会自动调整MatchCollection匹配对象中记录的范围开始和结束值。

处理此类事情的常用方法是向后遍历文档,即向后遍历段落,然后向后遍历匹配项。

这里出现的另一件事是m变量未声明。我认为它可能需要声明为Regex Match对象。

所以你需要更像这样的代码:

Sub lookForFields()
    '
    ' lookForFields Macro
    '
    Dim m As VBScript_RegExp_55.Match
    Dim theMatch As Long
    Dim thePara As Long
    Dim para As Paragraph
    Dim lineText As String
    Dim regEx As New RegExp
    Dim strPattern As String: strPattern = "\<(.*?)\>"
    Dim strInput As String
    Dim region As Word.Range
    Dim allmatches As MatchCollection
    Dim currentWord As String

    Debug.Print (vbCrLf + "------------------")
    Dim res As String
    With regEx
        .Global = True
        .MultiLine = False
        .IgnoreCase = True
        .Pattern = strPattern
    End With
    For thePara = ActiveDocument.Paragraphs.Count To 1 Step -1
      Set para = ActiveDocument.Paragraphs(thePara)
        txt = para.Range.Text
        Set allmatches = regEx.Execute(txt)
        For theMatch = allmatches.Count - 1 To 0 Step -1
          Set m = allmatches(theMatch)
            Set rng = ActiveDocument.Range(Start:=m.FirstIndex + para.Range.Start, End:=m.FirstIndex + Len(m.Value) + para.Range.Start)
            Set myField = ActiveDocument.Fields.Add(Range:=rng, Type:=wdFieldMergeField, Text:=m.Value)
            rng.HighlightColorIndex = wdYellow
        Next
    Next
    Set m = Nothing
    Set para = Nothing
End Sub