excel - 用于将 MS Word 表导出到 Excel 工作表的宏

标签 excel vba export ms-word

我有一个包含许多表格的Word文档。有谁知道如何编写宏将此类表导出到不同的 Excel 工作表?

最佳答案

答案取自:http://www.mrexcel.com/forum/showthread.php?t=36875

以下代码将 Word 中的表格读取到 Excel 的事件工作表中。如果 Word 包含多个表格,它会提示您输入 Word 文档以及表格编号。

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

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
    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 table number of table to import", "Import Word Table", "1")
    End If
    With .tables(TableNo)
        'copy cell contents from Word table cells to Excel cells
        For iRow = 1 To .Rows.Count
            For iCol = 1 To .Columns.Count
                Cells(iRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
            Next iCol
        Next iRow
    End With
End With

Set wdDoc = Nothing

End Sub

此宏应插入到 Excel(而不是 Word)中并放入标准宏模块中,而不是放入工作表或工作簿事件代码模块中。为此,请转到 VBA(键盘 Alt-TMV),插入宏模块 (Alt-IM),然后将代码粘贴到代码 Pane 中。像运行任何其他界面一样从 Excel 界面运行宏 (Alt-TMM)。

如果您的文档包含许多表格,例如您的 100 多页表格实际上是每个页面上的单独表格,则可以轻松修改此代码以读取所有表格。但现在我希望它都是一张连续的表,不需要任何修改。

<小时/>

保持卓越。

达蒙

VBAexpert Excel 咨询 (我的另一种生活:http://damonostrander.com)

关于excel - 用于将 MS Word 表导出到 Excel 工作表的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4465212/

相关文章:

vba - 从 VBA 末尾删除回车符(alt+enter)

c - 如何从 C 中导出结构体的字段

linux - 如何在 ksh 中导出函数?没有全局声明或使用自动加载

vba - 努力使用 Excel VBA 将文件附加到 Outlook 电子邮件

excel - 我想确定以黄色突出显示的按钮的正确代码

java - 使用 Jacob 1.18 从 Java 调用宏

c# - 如何创建 CSV Excel 文件 C#?

excel - 获取应用程序定义或对象定义的错误

java - 如何将 "fraction of day"转换为 Java 时间?

vba - CopyPaste中的应用程序定义或对象定义的错误