表格在word文档中常见的文档元素之一。操作word文件时有时需要提取文件中多个表格的内容到一个新的文件,甚至有时还会要提取题注信息。
今天,给大家分享两种批量提取文档中表格的两种方法,分别是VBA法和Python法两种。
一、VBA法提取word中的表格
1. 代码实现
VBA(Visual Basic for Applications)操作Word文件时,可以执行包括创建、打开、保存、修改文本和格式等多种任务。今天,我们使用VBA来批量提取当前文件中的表格,在每个表格中间添加一个空行。实现代码如下:
Sub ExtractTablesAndPreviousRowToNewFile()
Dim docSource As Document
Dim docTarget As Document
Dim tbl As Table
Dim rng As Range
Dim outputPath As String
Dim fileName As String
' 设置输出文件名和路径
fileName = "output.docx"
outputPath = ActiveDocument.Path & "\" & fileName
' 当前文档设置为源文档
Set docSource = ActiveDocument
' 创建一个新文档作为目标文档
Set docTarget = Documents.Add
For Each tbl In docSource.Tables
' 复制表格
tbl.Range.Copy
docTarget.Content.InsertParagraphAfter
docTarget.Content.Paragraphs.Last.Range.Paste
' 在表格后添加一个空行
docTarget.Content.InsertParagraphAfter
docTarget.Content.Paragraphs.Last.Range.InsertParagraphAfter
Next tbl
' 删