My current code to do this works when all instances of the string in the document are accompanied by the associated numeral. However, where some instances of "dog" arent followed by "102", but some are, the code fails to return "102", i.e. doesn't pick up the reference numeral, instead concluding that no numeral can be found. Here is my code:
Sub FindRefNumeral()
Dim targetString As String
Dim foundRange As Range
Dim numeral As String
' Get user input
targetString = InputBox("Feature:")
' Search the document
Set foundRange = ActiveDocument.Content
With foundRange.Find
.text = targetString & " [0-9]{1,3}" & "[A-Za-z]*"
.MatchWildcards = True
If .Execute Then
' Extract the numeral
numeral = Split(foundRange.text, " ")(UBound(Split(foundRange.text, " ")))
MsgBox "Reference numeral: " & numeral
Else
MsgBox "No reference numeral found."
End If
End With
End Sub
I want the macro to scan the document for any instances of that string (i.e., "dog") associated with a reference numeral, and outputs in a text box the reference numeral associated with the string, i.e., "102". I also want the macro to be robust to erroneous numerals in the document, i.e. if both "dog 102" and "dog 103" are present, I'd like the macro to output the numeral that most commonly follows the string - since this is probably the correct one.
(Only if no numeral is associated with that string, i.e., no instances of the requested string are found preceding a reference numeral, do I want the output text box to display "no numeral".)
This seems like it should be an easy fix, presumably involving looping through all instances of the string in the document, functionality which the code doesn't have yet. Any ideas?
"[A-Za-z]*"
to your search term?