
excel
使用excel VBA打开word模板并填充内容,然后将其另存为.docx文件的案例代码如下:
Sub FillwordTemplate() Dim wdApp As Object Dim wdDoc As Object Dim ws As Worksheet Dim rng As Range Dim savePath As String '设置word模板路径 Dim templatePath As String templatePath = "C:\Template.docx" '设置保存路径 savePath = "C:\Output.docx" '创建word应用程序对象 Set wdApp = CreateObject("word.Application") wdApp.Visible = True '打开word模板 Set wdDoc = wdApp.Documents.Open(templatePath) '设置excel工作表对象 Set ws = ThisWorkbook.Sheets("Sheet1") '获取要填充的内容范围 Set rng = ws.Range("A1:B10") '将excel中的数据填充到word模板中 rng.Copy wdApp.Selection.PasteexcelTable LinkedToexcel:=False, wordFormatting:=False, RTF:=False Application.CutCopyMode = False '另存为.docx文件 wdDoc.SaveAs2 savePath, FileFormat:=16 '关闭word对象 wdDoc.Close SaveChanges:=False wdApp.Quit '释放对象 Set wdDoc = Nothing Set wdApp = Nothing MsgBox "word模板已填充并保存为.docx文件。"End Sub下面是 的一篇文章,并在中间段落中添加标题并加上标签:Sub GenerateArticle() Dim wdApp As Object Dim wdDoc As Object Dim ws As Worksheet Dim rng As Range Dim savePath As String '设置word模板路径 Dim templatePath As String templatePath = "C:\Template.docx" '设置保存路径 savePath = "C:\Output.docx" '创建word应用程序对象 Set wdApp = CreateObject("word.Application") wdApp.Visible = True '打开word模板 Set wdDoc = wdApp.Documents.Open(templatePath) '设置excel工作表对象 Set ws = ThisWorkbook.Sheets("Sheet1") '获取要填充的内容范围 Set rng = ws.Range("A1:B10") '将excel中的数据填充到word模板中 rng.Copy wdApp.Selection.PasteexcelTable LinkedToexcel:=False, wordFormatting:=False, RTF:=False Application.CutCopyMode = False '另存为.docx文件 wdDoc.SaveAs2 savePath, FileFormat:=16 '关闭word对象 wdDoc.Close SaveChanges:=False wdApp.Quit '释放对象 Set wdDoc = Nothing Set wdApp = Nothing '生成文章 Dim article As String article = "这是一篇 的文章。" article = article & vbCrLf & vbCrLf article = article & "这是中间的一段文字。" article = article & vbCrLf & vbCrLf article = article & "<strong>中间段落的标题</strong>" article = article & vbCrLf & vbCrLf article = article & "这是中间段落的内容。" article = article & vbCrLf & vbCrLf article = article & "这是最后一段文字。" '将文章插入到word模板中 Set wdApp = CreateObject("word.Application") Set wdDoc = wdApp.Documents.Open(savePath) wdDoc.Content.InsertAfter article '保存并关闭word对象 wdDoc.Save wdDoc.Close '释放对象 Set wdDoc = Nothing Set wdApp = Nothing MsgBox "文章生成完成。"End Sub以上代码可以通过excel VBA来实现打开word模板,填充内容,并在中间段落中添加标题并加上标签的功能。请根据实际情况修改模板路径、保存路径和要填充的内容范围。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号