为什么这个VB程序总是返回1作为页码?

时间:2014-10-27 01:17:41

标签: regex vb.net vba ms-word

此程序使用RegExp方法在MS Word文档中查找某些单词。找到每个匹配后,程序应该找到每个匹配的页面并创建一个字符串,可以输出该字符串以显示找到该关键字匹配的所有页面。它现在的编写方式,出于某种原因,它为每个页面输出一个“1”,无论它在哪个页面上找到。例如,如果在第1页,第5页和第22页上找到“鼠标”一词,则会输出1,1,1。

For Each Match In RegExp.Execute(oWord.ActiveDocument.Range.Text)
            myKeyWords(numKeywords) = Match.Value
    PageNumbers(numKeywords) = ""

    With myWordDoc.ActiveDocument.Range.Find
        .ClearFormatting()
        .Text = Match.value
        .Wrap = False
        .Forward = True
        Do While .Execute = True
           If PageNumbers(numKeywords) = "" Then
               PageNumbers(numKeywords) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
           Else
              PageNumbers(numKeywords) = PageNumbers(numKeywords) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
           End If
        Loop
    End With

1 个答案:

答案 0 :(得分:1)

numKeywords没有递增。我没有

写出来
For Each Match In RegExp.Execute(oWord.ActiveDocument.Range.Text)

请注意,如果您在regexp方法之外使用此函数,则需要更改.Text = myKeywords(x)并在查找之前删除.range。

PageNumbers(numKeywords) = ""
For x = LBound(myKeywords) To UBound(myKeywords)
    PageNumbers(x) = ""
    With myWordDoc.ActiveDocument.Find
        .ClearFormatting()
        .Text = myKeywords(x)
        .Wrap = False
        .Forward = True
        Do While .Execute = True
           If PageNumbers(numKeywords) = "" Then
               PageNumbers(numKeywords) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
           Else
              PageNumbers(numKeywords) = PageNumbers(numKeywords) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
           End If
        Loop
    End With