vba-操作word替换指定字符

发布时间 2023-03-24 10:50:15作者: TimeNoMuch

Private Sub CommandButton生成Word文件_Click()
Dim Word对象 As New Word.Application
Dim 模板路径, 模板文件名, 导出路径, 导出文件名, 数据表名, 数据表数据起始行号, 数据表数据终止行号
Dim i, 判断, jStr1, Str2

模板路径 = Range("B2") & "\"
If Range("B2") = "当前" Then
模板路径 = ThisWorkbook.Path & "\"
End If
模板文件名 = Range("B3")
导出路径 = Range("B4") & "\"
If Range("B4") = "当前" Then
导出路径 = ThisWorkbook.Path & "\"
End If
导出文件名 = Range("B5")
数据表名 = Range("B6")
数据表数据起始行号 = Val(Range("B7"))
数据表数据终止行号 = Val(Range("B8"))

判断 = 0
'FileCopy 模板路径 & 模板文件名, 导出路径 & 导出文件名
With Word对象
.Documents.Open 导出路径 & 导出文件名
.Visible = False
.ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument '设置位置在正文
If 数据表数据终止行号 > 数据表数据起始行号 Then
.Selection.WholeStory '全选
.Selection.Copy '复制
For i = 数据表数据起始行号 To 数据表数据终止行号 - 1 '复制页
.Selection.EndKey Unit:=wdStory '全选
.Selection.InsertBreak Type:=wdPageBreak '分页
.Selection.PasteAndFormat (wdPasteDefault) '粘贴
Next i
End If
For i = 数据表数据起始行号 To 数据表数据终止行号
Str1 = "数据001"
Str2 = Sheets("各乡镇汇总").Range("A" & i)
.Selection.HomeKey Unit:=wdStory '光标置于文件首
If .Selection.Find.Execute(Str1) Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str2 '替换字符串
End If
Str1 = "数据002"
Str2 = Sheets("各乡镇汇总").Range("E" & i)
.Selection.HomeKey Unit:=wdStory '光标置于文件首
If .Selection.Find.Execute(Str1) Then '查找到指定字符串
.Selection.Font.Color = wdColorAutomatic '字符为自动颜色
.Selection.Text = Str2 '替换字符串
End If
Next i
End With
Word对象.Documents.Save
Word对象.Quit
Set Word对象 = Nothing
If 判断 = 0 Then
i = MsgBox("已生成“" & 导出路径 & 导出文件名 & "”!", 0 + 48 + 256 + 0, "提示:")
End If
End Sub