透過自動化僅將表格從 Microsoft Word 傳輸到 Excel

透過自動化僅將表格從 Microsoft Word 傳輸到 Excel

有沒有一種方法可以自動將資訊從 Microsoft Word 表格複製到 Microsoft Excel 表格?

答案1

是的,這很有可能。正如我證明了就在昨天,您還可以透過 VBScript 使用 Word 和 Excel 自動化來執行 VBA 支援的任何操作。嘗試以下 VBS 腳本:

Option Explicit

Dim objWord, objDoc, objExcel, objSheet, tbl, srcRow, dstRow, col, cell

Set objWord = CreateObject("Word.Application")
objWord.Visible = False
objWord.DisplayAlerts = False
objWord.Documents.Open "C:\MyDoc.docx", False, True ' path, confirmconversions, readonly
Set objDoc = objWord.ActiveDocument

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
objExcel.Workbooks.Add
Set objSheet = objExcel.ActiveSheet

dstRow = 0
For Each tbl In objDoc.Tables
    For srcRow = 1 To tbl.Rows.Count
        col = 0
        For Each cell In tbl.Rows(srcRow).Cells
            col = col + 1
            objSheet.Cells(dstRow+srcRow, col).Value = Left(cell.Range.Text, Len(cell.Range.Text)-1)
        Next
    Next
    dstRow = dstRow + SrcRow
Next

objWord.Quit 0 ' wdDoNotSaveChanges
Set objWord = Nothing
Set objDoc = Nothing

objExcel.ActiveWorkbook.SaveAs "C:\MyBook.xlsx"
objExcel.Quit
Set objExcel = Nothing
Set objSheet = Nothing

MsgBox "All table data copied from document to workbook!"

相關內容