|
来个最笨的,把模板中的四个数据分别改成“数据001”,“数据002”,“数据003”,“数据004”
Private Sub CommandButton生成Word文件_Click()
Dim Word对象 As New Word.Application, 当前路径, 导出文件名, 导出路径文件名, 判断, i, j
Dim Str1, Str2, Str3
当前路径 = ThisWorkbook.Path
最后行号 = Sheets("数据").Range("B65536").End(xlUp).Row
判断 = 0
导出文件名 = "工资通知.doc"
导出路径文件名 = 当前路径 & "\" & 导出文件名
FileCopy 当前路径 & "\工资通知(模板).doc", 导出路径文件名
With Word对象
.Documents.Open 导出路径文件名
.Visible = True
.ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument '设置位置在正文
.Selection.WholeStory '全选
.Selection.Copy '复制
Str1 = Sheets("数据").Cells(2, 2)
Str2 = Sheets("数据").Cells(2, 3)
Str3 = Sheets("数据").Cells(2, 4)
If .Selection.Find.Execute("数据001") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str1 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
If .Selection.Find.Execute("数据002") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str2 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
If .Selection.Find.Execute("数据003") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str1 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
If .Selection.Find.Execute("数据004") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str3 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
If 最后行号 > 3 Then
For i = 2 To 最后行号 - 1 '复制页
.Selection.EndKey Unit:=wdStory '光标置于文件尾
.Selection.InsertBreak Type:=wdPageBreak '分页
.Selection.PasteAndFormat (wdPasteDefault) '粘贴
.Selection.HomeKey Unit:=wdStory
Str1 = Sheets("数据").Cells(i + 1, 2)
Str2 = Sheets("数据").Cells(i + 1, 3)
Str3 = Sheets("数据").Cells(i + 1, 4)
If .Selection.Find.Execute("数据001") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str1 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
If .Selection.Find.Execute("数据002") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str2 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
If .Selection.Find.Execute("数据003") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str1 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
If .Selection.Find.Execute("数据004") Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str3 '替换字符串
.Selection.MoveRight Unit:=wdCharacter, Count:=1
End If
Next i
End If
End With
Word对象.Documents.Save
Word对象.Quit
Set Word对象 = Nothing
If 判断 = 0 Then
i = MsgBox("已生成“" & 导出路径文件名 & "”!", 0 + 48 + 256 + 0, "提示:")
End If
End Sub
|
评分
-
1
查看全部评分
-
|