将表格从Word复制到Excel。格式化

时间:2019-05-31 09:14:25

标签: excel vba ms-word

我正在尝试从Word文档中的13个表中提取数据。 通过Google和其他网站,我弄清楚了如何从表格中提取所有数据。但是,我想保留格式,因为Word文档中同时包含粗体和项目符号。

有人可以帮我吗?基本上,将所有表格从Word手动复制/粘贴到Excel中,包括格式设置。

我现在的代码是这样:

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

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

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

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

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 = 1
For tableStart = TableNo 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) = .cell(iRow, iCol).Range.Text
            Next iCol
            resultRow = resultRow + 1
        Next iRow
    End With
    resultRow = resultRow + 1
Next tableStart


End With

End Sub

0 个答案:

没有答案