VBA提取Word表格指定单元格内容并按行拆分至Excel
VBA提取Word表格指定单元格内容并按行拆分至Excel
本代码演示如何从Word文档中获取所有表格的(4,2)单元格内容,并将其按行拆分后写入Excel表格。
Sub SplitTableContent()
Dim objWord As Object
Dim objDoc As Object
Dim objTable As Object
Dim objCell As Object
Dim strText As String
Dim arrText() As String
Dim i As Long, j As Long
Dim objExcel As Object
Dim objSheet As Object
'打开Word文档
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Users\username\Desktop\test.docx")
'创建Excel文件
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objSheet = objExcel.Workbooks.Add.Sheets(1)
'循环遍历文档中的所有表格
For Each objTable In objDoc.Tables
'循环遍历表格中的指定单元格
For Each objCell In objTable.Cell(4, 2).Range.Cells
'获取单元格内容
strText = objCell.Range.Text
'去除空格和换行符
strText = Replace(strText, Chr(13), "")
strText = Replace(strText, Chr(7), "")
strText = Trim(strText)
'按行拆分
arrText = Split(strText, vbNewLine)
'将拆分后的内容写入Excel
For i = LBound(arrText) To UBound(arrText)
j = j + 1
objSheet.Cells(j, 1) = arrText(i)
Next i
Next objCell
Next objTable
'关闭Word文档和Excel文件
objDoc.Close
objWord.Quit
objExcel.Quit
Set objSheet = Nothing
Set objExcel = Nothing
Set objDoc = Nothing
Set objWord = Nothing
End Sub
代码说明:
- 变量声明: 声明了必要的变量,包括 Word 对象、文档对象、表格对象、单元格对象、文本字符串、字符串数组、循环计数器、Excel 对象、工作表对象等。
- 打开 Word 文档: 使用
CreateObject创建 Word 对象,并打开指定路径的 Word 文档。 - 创建 Excel 文件: 使用
CreateObject创建 Excel 对象,并创建一个新的工作簿,并使 Excel 窗口可见。 - 循环遍历表格: 使用
For Each循环遍历文档中的所有表格。 - 循环遍历单元格: 使用
For Each循环遍历指定单元格((4,2)单元格)。 - 获取单元格内容: 使用
objCell.Range.Text获取单元格内容,并去除空格和换行符。 - 按行拆分: 使用
Split函数按换行符将单元格内容拆分成字符串数组。 - 写入 Excel: 使用
For循环将拆分后的字符串数组内容写入 Excel 的第一列。 - 关闭文件: 关闭 Word 文档和 Excel 文件,并释放对象。
代码使用说明:
- 将代码复制到 VBA 编辑器中。
- 将代码中的
"C:\Users\username\Desktop\test.docx"替换为实际的 Word 文档路径。 - 运行代码,即可将指定单元格的内容按行拆分写入 Excel 表格。
注意:
- 本代码假设 Word 文档中的所有表格都包含 (4, 2) 单元格。
- 代码将内容写入 Excel 的第一列,可以根据需要修改代码写入其他列。
- 可以根据需要修改代码,例如:
- 指定其他单元格的位置
- 修改拆分方式
- 将内容写入其他工作表
原文地址: https://www.cveoy.top/t/topic/jr8b 著作权归作者所有。请勿转载和采集!