user1859440
user1859440

Reputation: 23

Word document extracts tables from the document only if

I'm working with this code. It opens a Word document extracts tables from the document and populate an Excel file. Everything works great for this part. Now I would like to populate the Excel file only if the first cell of word table contains this string "Row N#" and I'm blocked.

Here my code:

    Option Explicit

    Sub ImportWordTable()

    Dim wdDoc As Object
    Dim wdFileName As Variant
    Dim tableNo As Integer 'table number in Word

    Dim iRow As Long 'row index in Excel

    Dim iCol As Integer 'column index in Excel

    Dim resultRow As Long
    Dim tableStart As Integer
    Dim tableTot As Integer

    On Error Resume Next

    ActiveSheet.Range("A:AZ").ClearContents

    wdFileName = Application.GetOpenFilename("Word files (*.doc),*.doc", , _
    "Browse for file containing table to be imported")

    If wdFileName = False Then Exit Sub '(user cancelled import file browser)

    Set wdDoc = GetObject(wdFileName) 'open Word file

    With wdDoc
        tableNo = wdDoc.tables.Count
        tableTot = wdDoc.tables.Count
         If tableNo = 0 Then
           MsgBox "This document contains no tables", _
           vbExclamation, "Import Word Table"
        ElseIf tableNo > 1 Then
            tableNo = InputBox("This Word document contains " & tableNo & " tables." & vbCrLf & _
        "Enter the table to start from", "Import Word Table", "1")
    End If

    resultRow = 4

    For tableStart = 1 To tableTot
        With .tables(tableStart)
            If .tables(tableStart).Cell(1, 1).Range.Value = "Row N#" Then
            'copy cell contents from Word table cells to Excel cells

                For iRow = 1 To .Rows.Count
                    For iCol = 1 To .Columns.Count
                            Cells(resultRow, iCol) = WorksheetFunction.Clean(.Cell(iRow, iCol).Range.Text)
                    Next iCol
                    resultRow = resultRow + 1
                Next iRow
           End If
        End With
        resultRow = resultRow + 1
    Next tableStart
End With

End Sub

Upvotes: 1

Views: 557

Answers (1)

Dale M
Dale M

Reputation: 2473

Where is the End With for the wdDoc?

I don't think that you really mean to be looking for wdDoc.tables(tableStart).tables(tableStart).Cell(1, 1).Range.Value this is the first cell of the nth subtable of the nth table - lose one of the .tables(tableStart).

With statements seem like a good idea but they leave you open to this sort of mistake, especially when they are nested. Far more readable and less error prone to define a local table variable and assign to it at the beginning of the loop.

Also, I think this could be achieved much quicker and easier by utilising the cut and paste functionality

Upvotes: 0

Related Questions