|
Sub 批量生成打印word()
Application.ScreenUpdating = False
Dim i%, ar, myPath$, wdApp, wdD
Set d = CreateObject("scripting.dictionary")
myPath = ThisWorkbook.Path & "\"
Set wdApp = CreateObject("word.application")
wdApp.Visible = False
t = Timer
With Sheets("sheet1")
r = .Cells(Rows.Count, 1).End(xlUp).Row
ar = .Range("A1:q" & r)
End With
For i = 3 To UBound(ar)
If Trim(ar(i, 4)) <> "" Then
d(Trim(ar(i, 4))) = d(Trim(ar(i, 4))) + 1
End If
Next i
For Each k In d.keys
n = 0
ReDim br(1 To UBound(ar, 1), 1 To UBound(ar, 2))
For i = 2 To UBound(ar)
If Trim(ar(i, 4)) = k Then
n = n + 1
For j = 1 To UBound(ar, 2)
br(n, j) = ar(i, j)
Next j
End If
Next i
Set wdD = wdApp.Documents.Open(myPath & "采购合同.docx")
With wdD.Tables(1)
For i = 1 To n
For j = 6 To 11
.cell(i + 1, j - 4).Range.Text = br(i, j)
Next j
.cell(i + 1, 1).Range.Text = br(i, 1)
Next i
End With
For j = 1 To 17
wdApp.Selection.HomeKey unit:=6 '光标置于文件首
If wdApp.Selection.Find.Execute("数据" & Format(j, "000")) Then '查找到指定字符串
wdApp.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
wdApp.Selection.Text = br(1, j) '替换字符串
End If
Next j
wdD.PrintOut
wdD.SaveAs Filename:=myPath & Replace(k, "N0:", "合同号_") & ".docx"
wdD.Close
Next k
wdApp.Quit
Set wdD = Nothing
Set wdApp = Nothing
Set d = Nothing
Application.ScreenUpdating = False
MsgBox "耗时:" & Format(Timer - t, "0.00") & "秒!"
End Sub
|
|