Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find string in doc using wildcards; return full string VBA

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?

like image 835
Benjamin Dover Avatar asked Feb 03 '26 05:02

Benjamin Dover


1 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
like image 79
chris neilsen Avatar answered Feb 04 '26 22:02

chris neilsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!