如何批量将同结构Word文件的表格数据提取至Excel?
批量提取Word表格数据到Excel的VBA方案
可以通过VBA实现批量处理需求,以下是适配你场景的代码,能遍历Excel首列的所有文件路径,自动提取每个Word文件中的表格数据:
操作步骤
- 打开存放文件路径的Excel文件,按
Alt+F11打开VBA编辑器 - 右键左侧的
VBAProject,选择「插入」→「模块」 - 将以下代码粘贴到模块窗口中
批量处理代码
Sub BatchExtractWordTableData() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim wordApp As Object Dim doc As Object Dim tbl As Object Dim filePath As String ' 指定当前工作表 Set ws = ThisWorkbook.ActiveSheet ' 获取首列最后一行的行号 lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' 后台启动Word应用,不显示界面 Set wordApp = CreateObject("Word.Application") wordApp.Visible = False On Error Resume Next ' 捕获文件打开失败的异常 ' 遍历首列所有文件路径(假设第1行是表头,从第2行开始为路径) For i = 2 To lastRow filePath = ws.Cells(i, 1).Value If filePath <> "" Then Set doc = wordApp.Documents.Open(filePath) If Err.Number = 0 Then ' 获取文档内第一个表格(每个文件仅一个表格) Set tbl = doc.Tables(1) ' 提取表格数据:第1行第2列是Type值,第2行第2列是Price值 ws.Cells(i, 2).Value = tbl.Cell(1, 2).Range.Text ws.Cells(i, 3).Value = tbl.Cell(2, 2).Range.Text ' 清除Word单元格自带的末尾段落标记(多余字符) ws.Cells(i, 2).Value = Left(ws.Cells(i, 2).Value, Len(ws.Cells(i, 2).Value) - 2) ws.Cells(i, 3).Value = Left(ws.Cells(i, 3).Value, Len(ws.Cells(i, 3).Value) - 2) ' 关闭文档不保存 doc.Close SaveChanges:=False Else ws.Cells(i, 2).Value = "文件打开失败" Err.Clear End If End If Next i ' 退出Word应用 wordApp.Quit Set wordApp = Nothing Set doc = Nothing Set tbl = Nothing MsgBox "批量提取完成!" End Sub
关键说明
- 代码默认首列第1行是表头,若你的文件路径从第1行开始,将
For i = 2 To lastRow改为For i = 1 To lastRow - 针对你提供的表格结构,提取第1行第2列(Apple)和第2行第2列($5)的数据,若表格结构调整,修改
tbl.Cell(row, col)的行列参数即可 - 后台运行Word,避免弹窗干扰,同时提升处理效率
- 自动标记打开失败的文件,方便后续排查
内容的提问来源于stack exchange,提问作者Reginald Yau
相关产品推荐
相关产品推荐

