Home » excel » Excel VBA to import word data to excel

Excel VBA to import word data to excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am new to VBA I want to copy word tables to excel but I am not getting the REQ- part in excel, just getting other tabs

Input:
enter image description here

Desired output:
enter image description here

Output I get
enter image description here

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 resultCol As Long
Dim tableStart As Integer
Dim tableTot As Integer
On Error Resume Next
ActiveSheet.Range("A:AZ").ClearContents
wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
"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 = 2
    For tableStart = 1 To tableTot
        With .Tables(tableStart)
            'copy cell contents from Word table cells to Excel cells
            For iRow = 1 To .Rows.Count
                For iCol = 1 To .Columns.Count
                Range("A1") = "Description"
                Range("A1").Font.Bold = True
                Range("B1") = "Source"
                Range("B1").Font.Bold = True
                Range("C1") = "Rationale"
                Range("C1").Font.Bold = True
                    Cells(resultRow, iCol) = WorksheetFunction.Clean(.Cell(iCol, iRow).Range.Text)
                Next iCol
                resultRow = resultRow
            Next iRow
        End With
        resultRow = resultRow + 1
    Next tableStart
End With
End Sub
How to&Answers:

A number of adjustments were necessary in order to get this to work:

  1. On Error Resume Next has been removed. This should never be used for an entire macro – all it will do is hide errors that will tell you what’s going wrong. If errors are occurring regularly then something needs fixing! This can be used for special cases, but error handling should then be re-enabled. I see no special case in this code.

  2. Both Word and Excel use Range, so it’s important to specify what range is meant. This is also important in Excel, alone. Relying on VBA to guess in which worksheet a range is can lead to unexpected results. For this reason, a Worksheet object is declared and instantiated to the active worksheet. This object – ws – is then used throughout the code to clearly identify all Range objects in Excel.

  3. Since the column headings in Excel need to be written only once, that code has been moved out of the loop. Also, the first column is not labelled in the screen shot you provide (REQ). So labels should start with column B, not column A – those Range co-ordinates have been changed, accordingly.

  4. It’s always tricky, working with Word tables that have merged cells (first column in your screen shot). So the code to get the REQ is moved outside the table cell loop and references row 1, column 1 explicitly.

  5. The remainder of the data to be transferred is only in column 3, so there’s no need to loop columns, only rows. The column specifier for the Excel range has been modified to use irow + 1 as this gives the correct result.

  6. The Cell()method in Word is:.Cell(rowIndex, colIndex)` – the parameters are reversed in the code posted in the question.

The following code works for me in my tests:

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 resultCol As Long
    Dim tableStart As Integer
    Dim tableTot As Integer
    Dim ws As Worksheet

    'On Error Resume Next

    Set ws = ActiveSheet
    ws.Range("A:AZ").ClearContents

    wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
    "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 = 2
        With ws
            .Range("B1") = "Description"
            .Range("B1").Font.Bold = True
            .Range("C1") = "Source"
            .Range("C1").Font.Bold = True
            .Range("D1") = "Rationale"
            .Range("D1").Font.Bold = True
        End With
        For tableStart = tableNo To tableTot
            With .Tables(tableStart)
                'copy cell contents from Word table cells to Excel cells
                '''REQ
                ws.Cells(resultRow, 1) = WorksheetFunction.Clean(.Cell(1, 1).Range.Text)
                For iRow = 1 To .Rows.Count
                    'For iCol = 1 To .Columns.Count
                     ws.Cells(resultRow, iRow + 1) = WorksheetFunction.Clean(.Cell(iRow, 3).Range.Text)
                    'Next iCol
                    resultRow = resultRow
                Next iRow
            End With
            resultRow = resultRow + 1
        Next tableStart
    End With
End Sub