Вопрос

My Problem: I want to look for IDs in a Word Document which is something like " RS.1234/56.78910 "

My Code:

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

My Problem: Imho the RegExp seems to be fine BUT the Words.Count/Words.item split the ID into 7 words like:

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

Why not using " Document.Range.Find " ? -> I want to save the words to a variable and find the highest ID and I have no idea how to do this with range.find

Это было полезно?

Решение

You need to go through the whole document text instead of words.

Another thing, your Regexp doesn't work: you need to escape dots, and {4,4} should be {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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top