该VBA脚本可以实现从word文档的多个表中提取数据,每个表格的信息提取到一行。
Sub word2els()
Set wdApp = CreateObject(“kwps.application”)
path_ = ThisWorkbook.Path
wdApp.Documents.Open (path_ & “” & “bbb.doc”)
wdApp.Visible = True
ThisWorkbook.Sheets(“sheet1”).Cells(1, 1) = “序号” ‘’’ 设置sheet1的第一行第一列单元格内容为“序号”
ThisWorkbook.Sheets(“sheet1”).Cells(1, 2) = “用例标识” ‘’’ 设置sheet1的第一行第一列单元格内容为“用例标识”
ThisWorkbook.Sheets(“sheet1”).Cells(1, 3) = “测试类型” ‘’’ 设置sheet1的第一行第一列单元格内容为“测试类型”
n = wdApp.ActiveDocument.Tables.Count ‘’’'有多少个表格
excel_line_no = 2
For i = 1 To n
zhs = wdApp.ActiveDocument.Tables(i).cell(2, 2) ‘’'提取第i个表格的第二行第三列单元格的内容保存到变量zhs中
Version = wdApp.ActiveDocument.Tables(i).cell(3, 5) ‘’'提取第i个表格的第三行第五列单元格的内容保存到变量Version中
env = wdApp.ActiveDocument.Tables(i).cell(3, 7) ‘’'提取第i个表格的第三行第七列单元格的内容保存到变量env中
ThisWorkbook.Sheets(“Sheet1”).Cells(excel_line_no, 1) = zhs ‘’'将变量zhs的值写入到excel的sheet1的第’excel_line_no 行第1列
ThisWorkbook.Sheets(“Sheet1”).Cells(excel_line_no, 2) = Version ‘’'将变量Version的值写入到excel的sheet1的第’excel_line_no 行第2列
ThisWorkbook.Sheets(“Sheet1”).Cells(excel_line_no, 3) = env ‘’'将变量env的值写入到excel的sheet1的第’excel_line_no 行第3列
excel_line_no = excel_line_no + 1
Next
wdApp.Application.Quit '关闭word文档
Set wdApp = Nothing '释放对象变量的内存
End Sub
word文档如下:
提取结果如下: