.Find在Macro中不起作用,在手动进行时是

时间:2016-03-03 16:00:32

标签: vba word-vba

我试图在Word文档中找到正则表达式字符串<XE "i@>

背景:我正在建立一个索引,并自动选择要通过另一个宏添加的段落。有一些条目开始&#34; i。汽车 - 指汽车&#34;或&#34; ii。超级 - 意味着非常好&#34;。我想从索引条目中删除编号部分,因此想办法是查找{XE "i. Automobile ...}部分,然后使用RegEx删除i.

当我手动搜索我的字符串时,它可以正常工作并获取匹配项。但是,我的宏不起作用。单步执行,然后我到While .Execute下一步步骤转到Wend然后End With确实询问我是否要从头开始搜索,因此.Find有点工作,但为什么找不到任何匹配?

非常感谢任何建议!

Sub Hide_Roman_Numerals_from_Index()
Dim defText As String
Dim regExSearch As String
Dim oRng As Word.Range, rng As Word.Range

If ActiveWindow.ActivePane.View.ShowAll = False Then
    ActiveWindow.ActivePane.View.ShowAll = True
End If

Set oRng = ActiveDocument.Range
'Call ClearFindAndReplaceParameters(oRng)
regExSearch = "<XE ""i@>"
oRng.Find.ClearFormatting
With oRng.Find
        .Text = regExSearch
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    While .Execute
        Set rng = oRng.Paragraphs(1).Range
        rng.Select
    Wend
End With

If ActiveWindow.ActivePane.View.ShowAll = True Then
    ActiveWindow.ActivePane.View.ShowAll = False
End If
'Call ClearFindAndReplaceParameters(oRng)
End Sub

1 个答案:

答案 0 :(得分:1)

我认为如果我的问题得到解决,这种方法将适合你。

'BruceWayne
Sub Colorgreenfromw()
Application.ScreenUpdating = False
Dim oPar As Paragraph
Dim oRng As Word.Range
For Each oPar In ActiveDocument.Paragraphs
    Set oRng = oPar.Range
    With oRng
        With .Find
            .ClearFormatting
            .Font.Color = wdColorGreen
            .Replacement.ClearFormatting
            .Text = "<XE ""i@>"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchWildcards = True
            .Execute
        End With
            If .Find.Found Then
                Set oRng = oPar.Range
                    oRng.Font.Color = wdColorGreen
                Set oRng = Nothing
            End If
    End With
Next
End Sub