1. 程式人生 > >VBA批量生成word(如offer)

VBA批量生成word(如offer)

Excel裡面有客戶的名字、身份證、性別、手機號,通過批量更新offer的這4個變數批量生成offer。

VBA程式碼如下:
Sub CreateWord()
Dim mypath, Newname, i, XB, wApp
mypath = ThisWorkbook.Path & “\”
For i = 2 To [a1048576].End(xlUp).Row
Newname = “offer-” & Range(“a” & i) & “.docx” ‘給新生成的表起個名稱
FileCopy mypath & “offer.docx”, mypath & Newname ‘將模板複製並重命名
Set wApp = CreateObject(“word.application”)
With wApp
.Visible = False
.Documents.Open mypath & Newname ‘開啟我們複製的新檔案進行更改
Do While .Selection.Find.Execute(“名字”) ‘尋找客戶這個關鍵詞,將其用表格中的姓名來代替
.Selection.Text = Range(“A” & i).Text
.Selection.HomeKey Unit:=6
Loop

Do While .Selection.Find.Execute(“身份證號”)
.Selection.Text = Range(“B” & i).Text ‘替換字串
.Selection.HomeKey Unit:=6
Loop
Do While .Selection.Find.Execute(“男女”)
.Selection.Text = Range(“C” & i).Text ‘替換字串
.Selection.HomeKey Unit:=6
Loop
Do While .Selection.Find.Execute(“手機號”)
.Selection.Text = Range(“D” & i).Text ‘替換字串
.Selection.HomeKey Unit:=6
Loop

.Documents.Save
.Quit

End With
Next
Set wApp = Nothing

End Sub