|
- Sub 从Word中提取数据到Excel中()
- Dim WrdDocApp As Object, FSO As Object, wordFilePath, wordFilename, arr(), brr()
- Application.ScreenUpdating = False
- Set WrdDocApp = CreateObject("Word.Application") '用Set关键词创建Word应用程序对象!
- Set FSO = CreateObject("Scripting.FileSystemObject") '文件系统对象
- Set wordFilePath = FSO.GetFolder(ThisWorkbook.Path) '获取文件夹的路径
-
- wordFilename = Dir(wordFilePath & "\*.doc*") '循环查找Word,可以适应不同版本 具体提取哪类文件,根据文件扩展名进行处理
- Do While wordFilename <> "" '在目录中循环
- n = 0
- m = 0
-
- On Error Resume Next
- Set WrdDoc = GetObject(wordFilePath & "" & wordFilename) '使用此代码 ,打开Word文件 视窗会自动隐藏(给人的感觉是没有打开做的操作)
-
- ReDim arr(1 To 20, 1 To 10) '重新定义数组arr
- With WrdDoc.Tables(1) '提取Word文件内第1页的第1个表格内容
- Rem 第一部分
- arr(1, 1) = WorksheetFunction.Clean(.cell(1, 4).Range.Text) '合同号
- arr(1, 2) = WorksheetFunction.Clean(.cell(2, 2).Range.Text) '工程名称
- arr(1, 3) = WorksheetFunction.Clean(.cell(2, 4).Range.Text) '销售单号
- arr(1, 8) = WorksheetFunction.Clean(.cell(3, 2).Range.Text) '交货地址1
- x = .Rows.Count
- For i = 5 To x
- y = WorksheetFunction.Clean(.cell(i, 1).Range.Text)
- If y <> "收货人" Then
- n = n + 1
- ReDim Preserve brr(1 To 4, 1 To n)
- brr(1, n) = WorksheetFunction.Clean(.cell(i, 2).Range.Text)
- brr(2, n) = WorksheetFunction.Clean(.cell(i, 3).Range.Text)
- brr(3, n) = WorksheetFunction.Clean(.cell(i, 4).Range.Text)
- brr(4, n) = WorksheetFunction.Clean(.cell(i, 5).Range.Text)
- Else
- m = i
- Exit For
- End If
-
- Next
-
- arr(1, 9) = WorksheetFunction.Clean(.cell(m, 2).Range.Text) '收货人1
- arr(1, 10) = WorksheetFunction.Clean(.cell(m, 4).Range.Text) '联系电话1
-
- Rem 第二部分
- arr(n + 1, 8) = WorksheetFunction.Clean(.cell(m + 1, 2).Range.Text) '交货地址2
- arr(n + 1, 9) = WorksheetFunction.Clean(.cell(x, 2).Range.Text) '收货人2
- arr(n + 1, 10) = WorksheetFunction.Clean(.cell(x, 4).Range.Text) '联系电话2
- For i = m + 3 To x - 1
- y = WorksheetFunction.Clean(.cell(i, 1).Range.Text)
- If y <> "收货人" Then
- n = n + 1
- ReDim Preserve brr(1 To 4, 1 To n)
- brr(1, n) = WorksheetFunction.Clean(.cell(i, 2).Range.Text)
- brr(2, n) = WorksheetFunction.Clean(.cell(i, 3).Range.Text)
- brr(3, n) = WorksheetFunction.Clean(.cell(i, 4).Range.Text)
- brr(4, n) = WorksheetFunction.Clean(.cell(i, 5).Range.Text)
- Else
- Exit For
- End If
-
- Next
-
-
- End With
- myrows = Cells(Rows.Count, 4).End(3).Row + 1
- Range("A" & myrows).Resize(n, 10) = arr '把提取的内容赋值给Excel工作表
- Range("D" & myrows).Resize(n, 4) = Application.Transpose(brr)
- Erase arr '重新初始化arr数组
- Erase brr
- With Range("A2:J" & Cells(Rows.Count, 4).End(3).Row) '设定格式
- .Font.Size = 11: .Borders.Value = 1
- .HorizontalAlignment = xlCenter
- .VerticalAlignment = xlCenter
- End With
- Range("H2:H" & Cells(Rows.Count, 4).End(3).Row).HorizontalAlignment = xlLeft '设定格式
- Columns("A:J").EntireColumn.AutoFit '自动栏宽
- ' WrdDoc.Close ' 关闭Word文件
- WrdDocApp.Quit '关闭Word程序
- Set WrdDocApp = Nothing '释放Word程序
- wordFilename = Dir
- Loop '结束循环
- Application.ScreenUpdating = True
- End Sub
复制代码 |
|