|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
我是用纯代码来解决一对多的数据合并。
第一:辅助列最后会有很多空行,表格不美观。
第二:后期还需要单独拆分成独立文件,还需要发给其他人。
操作步骤:提前把数据源合并好,Word模板表格配置分组后最大的行数,配置需要分组的列号(FieldColumn),运行就可以了。
- Sub myMailMerge()
- Dim i As Byte, r As Integer, intCount As Integer, FieldColumn As Byte, HeadName As String
- Dim MyPath As String
- Dim arr()
- Dim dic As Object
- Application.ScreenUpdating = False
- Set dic = CreateObject("Scripting.Dictionary")
- MyPath = ThisDocument.Path
- If (ThisDocument.MailMerge.State = 0) Then
- MsgBox ("没有合并数据源!")
- Exit Sub
- End If
- '设置分组字段的列号
- FieldColumn = 4
- intCount = 0
- With ThisDocument.MailMerge.DataSource
- .ActiveRecord = wdFirstRecord
- Do
- dic(.DataFields(FieldColumn).Value) = .DataFields(FieldColumn).Value
- intCount = intCount + 1
- .ActiveRecord = wdNextRecord
- Loop Until intCount = .RecordCount
- HeadName = .FieldNames(FieldColumn)
- End With
- arr = dic.keys()
- For i = 0 To UBound(arr)
- SQL = "SELECT * FROM `code_toMany$` where [" & HeadName & "]='" & arr(i) & "'"
- ThisDocument.MailMerge.DataSource.QueryString = SQL
-
- With ThisDocument.MailMerge
- .Destination = wdSendToNewDocument
- .SuppressBlankLines = True
- .Execute Pause:=False
- End With
-
- With ActiveDocument
- .Content.Characters.Last.Previous.Delete '删除新文档最后一个字符
- For r = .Tables(1).Rows.Count To 2 Step -1
- 'If Len(Application.CleanString(.Tables(1).Rows(i).Cells(1).Range.Text)) = 2 Then
- If .Tables(1).Rows(r).Cells(1).Range.Text = Chr(13) & Chr(7) Then
- .Tables(1).Rows(r).Delete
- Else
- Exit For
- End If
- Next
- .SaveAs FileName:=MyPath & "" & arr(i) & ".docx"
- .Close
- End With
- Next
- ThisDocument.MailMerge.DataSource.Close
- Application.ScreenUpdating = True
- MsgBox ("Very Good!!!")
- End Sub
复制代码
|
|