Friday, 3 August 2012

Selecting and copying all tables in a Word doc to Excel (Mac)

The examples I found online didn't support Mac or the functionality I was trying to get to.
So, I have an 80 page word document with tables littered about with requirements,to copy these tables into Word, create a new Macro and copy this code into the new subroutine.
I've made some alterations to other examples online in order to get this working with the older version of VBA that comes with Mac Office 2011.
  Dim C As Variant
  Dim R As Long
  Dim Tbl As Table
  Dim xlApp As Object
  Dim xlWkb As Object
  Dim xlWks As Object
  
  'Set the starting cell on the worksheet
  C = "A"
  R = 1

  'Attach to the open workbook
  On Error Resume Next
  Set xlApp = GetObject(, "Excel.Application")
  If xlApp Is Nothing Then _
  Set xlApp = CreateObject("Excel.Application")
    
  Set xlWkb = xlApp.ActiveWorkbook
    
  'Select the worksheet to copy the tables to
  Set xlWks = xlApp.Worksheets("Sheet1")
  For Each Tbl In ActiveDocument.Content.Tables
   Tbl.Range.FormattedText.Copy
     xlWks.Cells(R, C).Select
     xlWks.Paste
     ' Comment the following line out to remove the gap between pastes
     R = R + Tbl.Rows.Count + 1
   Next Tbl