我假设这个问题的答案将涉及一些VBA,因此我为什么在这里问它——请让我知道我是否应该在其他地方问我的问题。
我必须经常准备报告,其中包括为客户提供的建议列表。这些文档以 Word 文档形式呈现。报告中的每项建议均采用以下格式:
[Name of recommendation] ([Product code])
[Multiple-line description of recommendation]
“名称/产品代码”行应用了标题样式,描述应用了普通样式。
在我的 Excel 文件中,我可以创建一个包含我的所有建议的表格:
Name1 ..... Code1 ..... Description1
Name2 ..... Code2 ..... Description2
.....
NameN ... CodeN ..... DescriptionN
然后,我可以在 Excel 中将所有这些信息合并在一起,并通过邮件合并将其传递到 Word,但我似乎无法以创建我想要的标题样式的方式做到这一点。我假设我需要做一些 VBA 工作才能实现我想要的,但我以前从未使用过 VBA。我在这里需要遵循的基本想法是什么?
按照上面评论中的建议,我在 Microsoft 社区上询问是否可以将其作为简单的邮件合并来执行。有人告诉我,我想要做的事情不可能通过邮件合并实现,而是需要一些 VBA。
我没有任何使用 VBA 的经验,但 ChatGPT 能够为我提供以下内容,这似乎是一种明智的方法(发布在这里,以防其他人在邮件合并时遇到此限制):
Sub SimpleMailMerge()
Dim wdApp As Object
Dim wdDoc As Object
Dim ExcelSheet As Worksheet
Dim LastRow As Long
Dim i As Long
'Create an instance of Word
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
On Error GoTo 0
If wdApp Is Nothing Then
Set wdApp = CreateObject("Word.Application")
End If
'Path to your Word document template
Set wdDoc = wdApp.Documents.Open("C:\Path\to\your\Word\Template.docx")
'Set your Excel sheet
Set ExcelSheet = ThisWorkbook.Sheets("Sheet1") 'Change "Sheet1" to your sheet name
'Find the last row with data in column A
LastRow = ExcelSheet.Cells(ExcelSheet.Rows.Count, "A").End(xlUp).Row
'Loop through each row in Excel
For i = 2 To LastRow 'assuming row 1 contains headers
'Add Heading with style "Heading 3"
wdDoc.Paragraphs.Add.Style = wdApp.ActiveDocument.Styles("Heading 3")
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Text = ExcelSheet.Cells(i, 1).Value
'Add Body with style "Normal"
wdDoc.Paragraphs.Add.Style = wdApp.ActiveDocument.Styles("Normal")
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Text = ExcelSheet.Cells(i, 2).Value
'Insert a paragraph break between entries
wdDoc.Paragraphs.Add
Next i
'Show Word application
wdApp.Visible = True
'Close Excel without saving changes (optional)
ThisWorkbook.Close SaveChanges:=False
End Sub