Preserve formatting of Word table in Excel VBA

落花浮王杯 提交于 2020-01-03 03:05:27

问题


From another discussion, I was able to find this macro that imports a table from Word into Excel.

It works great but how I can make it keep the formatting of the Word table?

I have tried a few ways but can't quite get it working. Also is there a way to do more files at once and not just 1 at a time?

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)
            '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 With
        resultRow = resultRow + 1
    Next tableStart
End With

End Sub

回答1:


Copy tables with formats from multiple documents in the same directory.

Sub ImportWordTable()

    Dim WordApp As Object
    Dim WordDoc As Object
    Dim arrFileList As Variant, FileName As Variant
    Dim tableNo As Integer                            'table number in Word

    Dim tableStart As Integer
    Dim tableTot As Integer
    Dim Target As Range

    'On Error Resume Next

    arrFileList = Application.GetOpenFilename("Word files (*.doc; *.docx),*.doc;*.docx", 2, _
                                              "Browse for file containing table to be imported", , True)

    If Not IsArray(arrFileList) Then Exit Sub         '(user cancelled import file browser)

    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True

    Range("A:AZ").ClearContents
    Set Target = Range("A1")

    For Each FileName In arrFileList
        Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)

        With WordDoc
            tableNo = WordDoc.tables.Count
            tableTot = WordDoc.tables.Count
            If tableNo = 0 Then
                MsgBox WordDoc.Name & " contains no tables", vbExclamation, "Import Word Table"

            ElseIf tableNo > 1 Then
                tableNo = InputBox(WordDoc.Name & " contains " & tableNo & " tables." & vbCrLf & _
                                   "Enter the table to start from", "Import Word Table", "1")
            End If

            For tableStart = 1 To tableTot
                With .tables(tableStart)
                    .Range.Copy
                    'Target.Parent.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False
                    Target.Activate
                    ActiveSheet.Paste

                    Set Target = Target.Offset(.Rows.Count + 2, 0)
                End With
            Next tableStart

            .Close False
        End With

    Next FileName

    WordApp.Quit

    Set WordDoc = Nothing
    Set WordApp = Nothing
End Sub



回答2:


You can just copy the entire table from Word and then paste it in Excel using the PasteSpecial method of the Worksheet. The PasteSpecial method of the Worksheet has different options to the PasteSpecial method of a Range. One of these options is Format and the HTML setting applies the format of the Word table to the Excel range being pasted to.

The PasteSpecial method of the Worksheet just uses the active cell, so you have to Select the target Range first. Seems a bit ugly but I don't see an alternative.

Here's an example:

Option Explicit

Sub Test()
    Dim rngTarget As Range

    Set rngTarget = ThisWorkbook.Worksheets("Sheet1").Range("A1")

    WordTableToExcel "C:\Users\Robin\Desktop\foo1.docx", 1, rngTarget

End Sub

Sub WordTableToExcel(strWordFile As String, intWordTableIndex As Integer, rngTarget As Range)

    Dim objWordApp As Object
    Dim objWordTable As Object

    On Error GoTo CleanUp

    'get table from word document
    Set objWordApp = GetObject(strWordFile)
    Set objWordTable = objWordApp.Tables(intWordTableIndex)
    objWordTable.Range.Copy

    'paste table to sheet
    rngTarget.Select
    rngTarget.Parent.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:=False

CleanUp:
    'clean up word references
    Set objWordTable = Nothing
    Set objWordApp = Nothing

End Sub

Regarding your question about how to apply to multiple files - you can just keep calling this re-usable Sub for each word document and iterate over the tables in that document per the loop you have in your existing code.



来源:https://stackoverflow.com/questions/38666154/preserve-formatting-of-word-table-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!