0
votes

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

enter image description here

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.

1

1 Answers

3
votes

Search the range.

With Rng.Find
    .Text = "The economies of Northern Ireland "
    .Execute
    If .Found = True Then
        Rng.MoveEnd wdWord, 3
        Rng.Copy
    Else
        MsgBox "Not found"
    End If
End With

If the word document is already open (and you're sure it will be open every time) then I'd just lazily declare variables.

Dim oDoc as Word.Document
Set oDoc = Word.ActiveDocument
Dim oRng as Word.Range
Set oRng = oDoc.Content

But that's my personal opinion.