0
votes

I am creating an excel tool that is to copy a table from a section C.1 of the word document and paste it into a designated sheet in the excel file.

The way the word document is set up is such that the only contents of section C.1 is that table.

Sometimes the table in section C.1 is contained in a single page, but sometimes it breaks and spills into the next page.

Trying to use the table count/table number approach is really impractical here because of the sheer number of tables in the word file and often the table number of the table of interest also changes, but the section number never changes.

How can I tell VBA to go to the section C.1 and copy over the table to the designated worksheet in my excel file?

1
Better formatingMuldec
Think about how you would do that as a user in Word. Maybe try Word's built-in FIND functionality, to start? And record it in a macro? Or place the table in a bookmark or content control?Cindy Meister

1 Answers

0
votes

I have extensively tried to solve this problem, as I have almost exclusively worked in Word VBA with a large number of tables. There are few ways to solve this.

Easiest - Bookmarks

If you have access and permission to alter the source document, I would simply add a bookmark in either the desired table or the desired section-header and/or title. Then you can do something like:

Dim thisTbl as Range
Set thisTbl = ActiveDocument.GoTo(what:=wdGoToBookmark, Name:="bookmark").Tables(1).Range

or

Dim thisTbl as Range
Set thisTbl = ActiveDocument.GoTo(what:=wdGoToBookmark, Name:="bookmark").Paragraphs(1).Range
Set thisTbl = thisTbl.GoTo(what:=wdGoToTable, which:=wdGoToNext).Tables(1).Range

Second Easiest

Determine a word or phrase that is specific to that table and/or section-header and/or title. Then define a range, search across the document, and set the range equal to the Find results. Then manipulate the range as mentioned above, so that it looks something like this:

Dim thisTbl as Range
Set thisTbl = ActiveDocument.Content

With thisTbl.Find
    .ClearFormatting
    .Text = "Specific to the table/header"
    .Wrap = wdFindStop
    .Execute 
    'If your find criteria is specific to the table, stop here. Otherwise, execute the following to move down a table: 
    If .Found = True Then
       Set thisTbl = thisTbl.GoTo(what:=wdGoToTable, which:=wdGoToNext).Tables(1).Range
    End If

End With

It sounds to me like "C.1" is the phrase you should be looking for, if you can't set a bookmark.

As far as the spilling over goes, that shouldn't matter if you're setting a range, unless the table is broken with a wdColumnBreak. If that is the case, I suggest adding in a check for Range.Information.

Importing to Excel

There are lots of good guides out there on how to do this. The easiest way is to simply use a Range.Copy inside Word and .Paste inside Excel.