Word VBA:在页面上搜索特定字符串

时间:2015-08-04 14:25:39

标签: vba ms-word word-vba

我想在一个大的ms-Word文档上搜索很多文章名称,所以,我问我怎么能做这样的事情?

'To find exactly this string
    Selection.Find.Text = "Article : KR"
'To find all the other strings ("Article : [NOT KR]")
    Selection.Find.Text = "Article : [!KR]"
'To compare Strings, i need to make a test, like this
    IF Selection.Find.Text = "Article : ^?^?" <> "Article : KR" Then Call SearchAndMarkx("artKR")
'To build a case structure maybe with the tests 
Case Selection.Find.Found "Article : KR" do ...
Case Selection.Find.Found "Article : IP" do ...

我想知道如何编写这些说明。 我需要知道如何做到这一点!我搜索了很多,我想要的结果仍然没有找到! 谢谢你的考虑。

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式轻松匹配该模式。以下将匹配文章:KR(后跟空格或段落中断)然后匹配文章:[!KR](后面跟一个空格或段落)

Sub FindTags()

Dim myRange
Set myRange = Application.ActiveDocument.Content

Dim myFind
Set myFind = myRange.Find

Dim base
base = "Article : "
Dim srch
srch = base & "*[^13 ]"

While (myFind.Execute(FindText:=srch, MatchWildcards:=True))
    Dim difference, rangeLength, srchLength, text
    rangeLength = Len(myRange.text)
    srchLength = Len(base & "KR")
    difference = rangeLength - srchLength
    If (difference > 1) Then
        'Process your Article : [!KR] here
        text = Mid(myRange.text, Len(base) + 1, Len(myRange.text) - Len(base) - 1)
    Else
        text = Mid(myRange.text, Len(base) + 1, 2)
        If (text <> "KR") Then
            'Process your Article : [!KR] here
        Else
            'Process your Article : [KR] here
        End If

    End If
End Sub