将表从word复制粘贴到excel

时间:2014-02-24 21:10:57

标签: excel vba ms-word word-vba copy-paste

我有一个定期更新的word文档。我可以进入Word文档,选择整个表的内容并复制,然后进入Excel电子表格并粘贴它。搞砸了;但是,我修复如下:

    sht.Cells.UnMerge
    sht.Cells.ColumnWidth = 14
    sht.Cells.RowHeight = 14
    sht.Cells.Font.Size = 10

无论表格是否包含合并字段,此手动复制粘贴都可以使用。 然后我可以开始手动操作它:解析,检查,计算等。

我一次只能做一张桌子,但这很乏味,当然也容易出错。

我想自动化这个。我找到了一些代码:

Sub read_word_document()

Dim sht As Worksheet

Dim WordDoc As Word.Document
Dim WordApp As Word.Application

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

On Error GoTo ErrHandler

Set WordDoc = WordApp.Documents.Open("Z:\mydir\myfile1.DOC", ReadOnly:=True)


j = 0
For i = 1 To WordDoc.Tables.Count
    DoEvents
    Dim s As String
    s = WordDoc.Tables(i).Cell(1, 1).Range.Text
        Debug.Print i, s
        WordDoc.Tables(i).
        Set sht = Sheets("temp")
        'sht.Cells.Clear
        sht.Cells(1, 1).Select
        sht.PasteSpecial (xlPasteAll)

    End If
Next i

WordDoc.Close
WordApp.Quit

GoTo done

ErrClose:
  On Error Resume Next

ErrHandler:

Debug.Print Err.Description

On Error GoTo 0

done:

End Sub

当然这会一次又一次地覆盖同一张表 - 这没关系。这只是一个考验。问题是这适用于那些没有合并单元格的表。但是,如果表已合并单元格,则会失败。我无法控制我得到的文件。它包含近百个表。有没有办法复制粘贴我手动执行操作时的确切方法?

1 个答案:

答案 0 :(得分:5)

这样的事情:

Sub read_word_document()

Const DOC_PATH As String = "Z:\mydir\myfile1.DOC"

Dim sht As Worksheet
Dim WordDoc As Word.Document
Dim WordApp As Word.Application
Dim i As Long, r As Long, c As Long
Dim rng As Range, t As Word.Table

    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = False
    Set WordDoc = WordApp.Documents.Open(DOC_PATH, ReadOnly:=True)

    Set sht = Sheets("Temp")
    Set rng = sht.Range("A1")
    sht.Activate

    For Each t In WordDoc.Tables
        t.Range.Copy
        rng.Select
        rng.Parent.PasteSpecial Format:="Text", Link:=False, _
                    DisplayAsIcon:=False
        With rng.Resize(t.Rows.Count, t.Columns.Count)
            .Cells.UnMerge
            .Cells.ColumnWidth = 14
            .Cells.RowHeight = 14
            .Cells.Font.Size = 10
        End With

        Set rng = rng.Offset(t.Rows.Count + 2, 0)
    Next t
    WordDoc.Close
    WordApp.Quit
End Sub