|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
Sub 生成word文档()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim i%, ar, myPath$, wdApp, wdd
Dim oFso
Set oFso = CreateObject("Scripting.FileSystemObject")
myPath = ThisWorkbook.Path & "\"
wj = myPath & "欠费通知函.docx"
f = Dir(wj)
If f = "" Then MsgBox "找不到欠费通知函.docx,请核查后重试!": End
Set wdApp = CreateObject("word.application")
wdApp.Visible = True
With Sheets("a")
rs = .Cells(Rows.Count, 1).End(xlUp).Row
If rs < 3 Then MsgBox "数据源为空!": End
ar = .Range("A2:e" & rs)
End With
For i = 2 To UBound(ar)
If Trim(ar(i, 2)) <> Empty Then
FileCopy myPath & f, myPath & "通知单\" & ar(i, 2) & "-欠费通知函.docx"
Set wdd = wdApp.Documents.Open(myPath & "通知单\" & ar(i, 2) & "-欠费通知函.docx")
With wdApp.Selection
.HomeKey unit:=6 '光标置于文件首
If .Find.Execute("sj1") Then '查找到指定字符串
.Font.Color = wdColorAutomatic '字符为自动颜色
.Text = ar(i, 2) '替换字符串
End If
End With
With wdApp.Selection
.HomeKey unit:=6 '光标置于文件首
If .Find.Execute("sj2") Then '查找到指定字符串
.Font.Color = wdColorAutomatic '字符为自动颜色
.Text = ar(i, 5) '替换字符串
End If
End With
wdd.Close True
End If
Next i
wdApp.Quit
Set wdd = Nothing
Set wdApp = Nothing
Set oFso = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "通知单已生成完毕!", vbInformation
End Sub
|
|