Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy one section of text from Word to Excel using an Excel macro?

I need to copy a specific item of text (one or a few words) from Word (2007) to Excel (2007) using an Excel macro, for multiple documents.

So far I have the Excel macro opening each Word document one at a time and locating the text adjacent to what I need.

I now need to:

  1. Move to an adjacent cell in a Word table. I'm thinking wdApp.Selection.MoveLeft Unit:=wdCell (or MoveRight) where wdApp is Word.Application
  2. Copy the contents of the cell. I'm thinking wdApp.Selection.Copy and something like wdDoc.Word.Range where wdDoc is Word.Document but I can't select the whole cells contents.
  3. Paste it into a variable in Excel. Here I don't know how to copy the clipboard to an Excel variable.
like image 227
Reinstate Monica - Goodbye SE Avatar asked Sep 07 '11 17:09

Reinstate Monica - Goodbye SE


People also ask

How do you scrape data from Word to Excel?

Open a blank worksheet in Excel. Go to Data | Import External Data | Import Data. (In Excel 2007, click the Data tab, click Get External Data, and then select From Text.) Click the text file you want to import, then click Import.

How do I extract specific text from a Word document?

Open the DOCX file and click on File > Save As > Computer > Browser. Choose to save file as Plain Text (for XLSX files, save it as Text (Tab delimited)). Locate and open the text file with the name you have used to save it. This text file will contain only the text from your original file without any formatting.


1 Answers

Updated to show searching for text and then selecting content relative to its location:

Sub FindAndCopyNext()

    Dim TextToFind As String, TheContent As String
    Dim rng As Word.Range

    TextToFind = "wibble" 'the text you're looking for to
                          ' locate the other content

    Set rng = wdApp.ActiveDocument.Content
    rng.Find.Execute FindText:=TextToFind, Forward:=True

    If rng.Find.Found Then
        If rng.Information(wdWithInTable) Then
          TheContent = rng.Cells(1).Next.Range.Text      'move right on row
          'TheContent = rng.Cells(1).Previous.Range.Text 'move left on row
          MsgBox "Found content '" & TheContent & "'"
        End If
    Else
        MsgBox "Text '" & TextToFind & "' was not found!"
    End If

End Sub

Then assign the variable TheContent to your required Excel range.

like image 56
Tim Williams Avatar answered Sep 23 '22 16:09

Tim Williams