gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:52:21 25 4
gpt4 key购买 nike

我有一个包含许多表格的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com