利用VBA提取Excel表格数据到Word中
Excel表格数据如下所示,并创建一个Button命令按钮:
首先在word中新建一个空的表格:
按Alt+F11进入代码界面,输入以下代码并保存:
Option Explicit
Private Sub Word表格数据_Click()
Dim wdDoc As Object
Dim wdFileName As Variant
Dim tableNo As Integer 'Word中表的数量
Dim iRow As Long 'Excel的行
Dim iCol As Integer 'Excel的列
Dim resultRow As Long
Dim tableStart As Integer
Dim tableTot As Integer
On Error Resume Next
ActiveSheet.Range("A:AZ").ClearContents
wdFileName = Application.GetOpenFilename("Word files (*.doc*),*.doc*", , _
"浏览包含要导入的表的文件")
If wdFileName = False Then Exit Sub '用户取消导入文件浏览
Set wdDoc = GetObject(wdFileName) '打开Word文件
With wdDoc
tableNo = wdDoc.tables.Count
tableTot = wdDoc.tables.Count
If tableNo = 0 Then
MsgBox "这个Word文件不包含表格", _
vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox("该Word文件包含了" & tableNo & "张表。" & vbCrLf & _
"开始导入!", "导入Word表格", "1")
End If
resultRow = 4
For tableStart = 1 To tableTot '这个表示从第几个表格开始处理
With .tables(tableStart) '将单元格内容从 Word 表格复制到 Excel 单元格
For iRow = 1 To .Rows.Count '第几行表格开始处理
For iCol = 1 To .Columns.Count
Cells(resultRow, iCol) = WorksheetFunction.Clean(.Cell(iRow, iCol).Range.Text)
Next iCol
resultRow = resultRow + 1