实现VBA自动筛选并进行邮件合并。
代码示例:
Sub MailMerge_Filter() '定义邮件合并字段 Dim MailMergeField As String MailMergeField = "Department"
'设置邮件合并Word文档
Dim wdDoc As Object
Set wdDoc = CreateObject("Word.Application")
wdDoc.Visible = True
wdDoc.Documents.Open "C:\Test.docx"
'设置数据源
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Activate
ws.ListObjects("Table1").Range.AutoFilter Field:=1
'获取筛选条件
Dim FilterList() As String
FilterList = GetFilterList(ws, MailMergeField)
'依次筛选,并进行邮件合并
Dim i As Integer
For i = 1 To UBound(FilterList)
ws.ListObjects("Table1").Range.AutoFilter Field:=1, Criteria1:=FilterList(i)
'进行邮件合并
wdDoc.MailMerge.MainDocumentType = wdFormLetters
wdDoc.MailMerge.OpenDataSource "C:\Data.xlsx"
wdDoc.MailMerge.Destination = wdSendToNewDocument
wdDoc.MailMerge.Execute
'关闭数据源
wdDoc.MailMerge.DataSource.Close
Next i
'清除筛选,并关闭Word文档
ws.ListObjects("Table1").Range.AutoFilter
wdDoc.Close savechanges:=False
Set wdDoc = Nothing
MsgBox "邮件合并完成!"
End Sub
'获取筛选条件函数 Function GetFilterList(ws As Worksheet, fieldName As String) As String() Dim FilterList() As String Dim i As Integer Dim j As Integer Dim FoundMatch As Boolean
j = 1
For i = 2 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
FoundMatch = False
For Each item In FilterList
If item = ws.Cells(i, 1).Value Then
FoundMatch = True
End If
Next
If FoundMatch = False Then
'加入新条件
ReDim Preserve FilterList(1 To j)
FilterList(j) = ws.Cells(i, 1).Value
j = j + 1
End If
Next
GetFilterList = FilterList
End Function
说明:
本代码实现了VBA自动筛选并进行邮件合并。
首先定义邮件合并字段,然后设置邮件合并Word文档,接着设置数据源,获取筛选条件,依次筛选,并进行邮件合并。完成后清除筛选,并关闭Word文档。
GetFilterList函数用于获取筛选条件。
注意:本示例代码仅供参考,如需使用请根据实际情况进行修改。