Home » excel » excel – Find string in doc using wildcards; return full string VBA

excel – Find string in doc using wildcards; return full string VBA

Posted by: admin April 23, 2020 Leave a comment

Questions:

What I need to do is search a word document for a dollar amount and then return the amount to the program for user verification. I know the amount starts with a “$”, and ends with two digits after the decimal point (there’s only one amount per document). The search returns true like I want, but how do I actually pull the full figure from the word document (to be assigned to a variable)

Code below (Excel 2010); Cheers.

With wdDoc.Content.Find
   .Text = "$*.??"
   .MatchWildcards = True
   If .Execute Then
      'would be verified here
   Else
      'etc
   End If
End With

Edit:
I managed to get the following working;

   With wdApp.Selection.Find
      .Text = "$*.??"
      .Wrap = wdFindAsk
      .Forward = True
      .MatchWildcards = True
      If .Execute Then
         debug.print wdApp.Selection.Text
      Else
         debug.print "Not Found"
      End If
   End With

The only negative to this is that if the user managed to select a different word document while this search is running, it won’t find the result because the selection has changed. Is there any way to specifically search ONLY the active document opened earlier in the code? (“wdDoc”). Using wdDoc.Content doesn’t seem to have any way of returning the string.

Edit2: Is there a way to return text from a search using the Word.Document as opposed to the Word.Application?

How to&Answers:

You can use a Range object to reference to found text.

Also, the Find pattern $*.?? could find many things in your doc, other than what you want, should a stray $ exist.

You can use this pattern to find precisely a dollar amount

$[0-9]{1,}.[0-9]{2}

Sub Demo()
    Dim wdDoc As Document
    Dim oRng As Range

    ' Set reference to required doc
    Set wdDoc = ActiveDocument

    ' ....

    Set oRng = wdDoc.Content
    With oRng.Find
        .Text = "$[0-9]{1,}.[0-9]{2}"
        .Wrap = wdFindAsk
        .Forward = True
        .MatchWildcards = True

        If .Execute Then
           Debug.Print oRng
        Else
          'etc
        End If
    End With
End Sub

Answer:

Try this

With ActiveDocument.Content.Find
    .Text = "$*.??"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindAsk
    .MatchWildcards = True
    If .Execute Then
        Debug.Print Selection.Range.Text
    Else
        Debug.Print "not Found"
    End If
End With

FOLLOWUP

Try this (Tried And tested)

Sub Sample()
    ActiveDocument.Content.Select
    With Selection.Find
        .Text = "$*.??"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .MatchWildcards = True
        If .Execute Then
            Debug.Print Selection.Range.Text
        Else
            Debug.Print "not Found"
        End If
    End With
End Sub