VBA Word - Document.Words无法识别ID

时间:2014-04-30 08:33:11

标签: regex string vba ms-word find

我的问题:我想在Word文档中查找ID,如“RS.1234 / 56.78910”

我的代码:

Sub findIDs()

    Dim oDoc As Document
    Dim obj_RegEx As Object
    Dim nextID As String

    Set oDoc = ActiveDocument
    Set obj_RegEx = CreateObject("VbScript.RegExp")
    obj_RegEx.Pattern = "RS.[0-9]{4;4}/[0-9]{2;2}.[0-9]{5;5}"

    For i = 1 To oDoc.Words.Count
        If obj_RegEx.Test(oDoc.Words.Item(i).Text) = True Then
            Debug.Print "Found: " & oDoc.Words.Item(i).Text
        Else
            Debug.Print "Not Found: " & oDoc.Words.Item(i).Text
      End If
   Next

End Sub

我的问题:Imho RegExp似乎很好但是Words.Count / Words.item将ID分成7个单词,如:

RS.1234/56.78910" -> "RS" "." "1234" "/" "56" "." "78910"

为什么不使用“Document.Range.Find”? - >我想将单词保存到变量并找到最高ID,我不知道如何使用range.find

执行此操作

1 个答案:

答案 0 :(得分:0)

您需要浏览整个文档而不是单词。

另一件事,你的正则表达式不起作用:你需要转义点,而{4,4}应该是{4}

Sub findIDs()

    Dim oDoc As Document
    Dim obj_RegEx As Object
    Dim nextID As String
    Dim result As Variant
    Dim id As Variant

    Set oDoc = ActiveDocument
    Set obj_RegEx = CreateObject("VbScript.RegExp")
    obj_RegEx.Global = True 'match all occurrences
    obj_RegEx.Pattern = "RS\.[0-9]{4}/[0-9]{2}\.[0-9]{5}"

    Set result = obj_RegEx.Execute(oDoc.Content.Text)
    For Each id In result
            Debug.Print "Found: " & id.value
   Next

End Sub