An implementation of Visual Basic that is built into Microsoft products.
The script needs two main things to work reliably:
- Ensure the wildcard Find in the first window actually succeeds and returns text.
- Use the Find object correctly when searching in Window(2).
Below is a corrected and simplified version based on the standard Word Selection.Find pattern from the documentation, including wildcard use and a second Find using the captured text:
Sub Testing2()
Dim i As Integer
Dim blnFound As Boolean
Dim strText As String
' First window: find pattern with wildcards
With Selection.Find
.ClearFormatting
.Text = "[0-9]{1,} [A-Z]{1,}"
.Replacement.ClearFormatting
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
blnFound = .Execute
End With
If Not blnFound Then
MsgBox "No match found in Window 1.", vbExclamation
Exit Sub
End If
' Optional: update fields in the found selection
Selection.Fields.Update
' Capture the found text
strText = Selection.Text
' Collapse selection so next operations start at beginning of match
Selection.Collapse Direction:=wdCollapseStart
' Activate second window and search for the same text
Windows(2).Activate
With Selection.Find
.ClearFormatting
.Text = strText
.Replacement.ClearFormatting
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = True
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
' Find the 1st and 2nd occurrence
For i = 1 To 2
blnFound = .Execute
If Not blnFound Then
MsgBox "Occurrence " & i & " was not found in Window 2!", vbExclamation
Exit Sub
End If
Next i
End With
' Copy the entire line of the 2nd occurrence
Selection.HomeKey Unit:=wdLine
Selection.Extend
Selection.EndKey Unit:=wdLine
Selection.Copy
MsgBox "The 2nd occurrence has been copied successfully!", vbInformation
End Sub
Key points aligned with Word’s Find model in the documentation:
-
Selection.Find.ClearFormattingand.Replacement.ClearFormattingare called before setting criteria, as shown in the examples. - Wildcards are enabled only for the first search (
.MatchWildcards = True) and disabled for the second (.MatchWildcards = False). -
Executeis used on theFindobject and its Boolean return value (blnFound) is checked, matching the documented pattern forFind.Execute. -
Wrap = wdFindContinueis used so the search continues through the document if the end is reached.
If Windows(2) does not exist or is not a different view of the same document, the macro will fail at Windows(2).Activate; ensure a second window is open for the document before running the macro.
References: