My goal is to find unique text in the word document "The economies of Northern Ireland " and copy three consecutive words from this document. And I have to do this from excel VBA. The word document being searched, will be manually opened before VBA code is executed from .xlsm file. It's going to be the only opened .docx file at the time of VBA code execution, but the file name will always be different, therefore we cannot hardcode the .docx file name nor path.
Sub Find_Price()
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Dim TextToFind As String
Dim NumberToFind As String
Dim Rng As Word.Range
Application.ScreenUpdating = False
'This is the text I'm looking for in .ActiveDocument
TextToFind = "The economies of Northern Ireland "
NumberToFind = "82110907192"
'Reference already opened Word document from excel VBA console
Set WordApp = GetObject(, "Word.Application")
WordApp.Application.Visible = True
WordDoc.Select
Set Rng = WordApp.ActiveDocument.Content
'Set WordDoc = WordApp.Documents.Open(FilePath & "Form1.docx")
'Set WordDoc = WordApp.ActiveDocument 'I don't know how to finish this line :-(
'With WordApp.Content.Find.Execute.NumberToFind
With WordDoc.Content.Find.Execute.NumberToFind 'Code crashes in this line;
Rng.Find.Execute FindText:=TextToFind, Forward:=True
'what this "Forward:=True" means??
If Rng.Find.Found Then
If Rng.Information(wdWithInTable) Then
' I don't know how to write this part of the code.
' Please don't remove my question again - I've researched 16h for this info.
MsgBox "Price is " & TextToFind & " pln."
End If
Else
MsgBox "Text was not found!"
End If
End Sub
The code crashes on this line:
With WordDoc.Content.Find.Execute.NumberToFind
Most important thing for me is to:
1) perform a search on currently opened word doc, from excel vba editor,
2) find unique text = "The economies of Northern Ireland " in this word document,
3) and copy this text to a clipboard, so I could manually paste it into the cell of my choice.