如果文本使用vba具有字段索引,则无法在word文档中找到该文本

时间:2014-12-24 13:12:20

标签: vba word-vba

我需要在word 2007中找到以下文字

布冯{XE"布冯" 1997年

我在VBA中尝试使用选择方法,它运行正常。我使用范围做了这个,但它不起作用。有人可以帮帮我吗?

使用选择方法的代码:

ActiveDocument.ActiveWindow.View.ShowAll = False
ActiveDocument.ActiveWindow.View.ShowHiddenText = False

Selection.Find.ClearFormatting
With Selection.Find
    .Text = "Buffon 1997"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
If Selection.Find.Execute Then
    Selection.Range.Font.Bold = True
End If

它工作正常。

使用单词Range方法的代码:

Dim doc As Document, story As Range, tem As Range
Set doc = ActiveDocument

For Each story In doc.StoryRanges
    Set tem = story.Duplicate
    tem.Find.ClearFormatting
    With tem.Find
        .Text = "Buffon 1997"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .IgnorePunct = True
    End With

    If tem.Find.Execute() Then
        tem.Font.Bold = True
    End If
Next story

此代码无效。

1 个答案:

答案 0 :(得分:0)

我在这里搜索 Word 中的每个story时写了类似的答案:Word Macro to find and replace all in word document with textboxes

有关如何搜索每个story的文档,请访问:http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm

您应该可以跳过Set tem = story.Duplicate行,只需跳至With story.Find

即可