Public proType As String '定义一个公共变量,判断要不要打印
Sub mySplit()
Dim arrTem(), wb As Workbook
Dim ws As Worksheet, wsTarget As Worksheet
Dim arr()
dim dic As Object, dKey As String
Dim saveFolder As String, fileName As String
Dim iRows As Integer, k As Integer, i As Integer
Dim grandTotal As Double
Set ws = ThisWorkbook.Sheets("列表")
Set dic = CreateObject("Scripting.Dictionary")
Application.DisplayAlerts = False '略过警告信息,如覆盖已有文件。
Application.ScreenUpdating = False '停止屏幕刷新
If proType = "打印" Then '如果点击了“打印”命令按钮,选择打印机。
If Application.Dialogs(xlDialogPrinterSetup).Show = False Then
Exit Sub
End If
End If
With Application.FileDialog(msoFileDialogFolderPicker) '选择文件夹
.Title = "请选择保存文件夹......"
If .Show = -1 Then
saveFolder = .SelectedItems(1)
Else
MsgBox "请选择文件保存文件夹!"
Exit Sub
End If
End With
arr = ws.UsedRange '把列表装入数组
For i = 2 To UBound(arr) '循环数组
dKey = arr(i, Pxy(arr, "代理人", 2)) '代理人作为字典的Key。
If Not dic.exists(dKey) Then '如果dkey不存在
k = 0
Else
arrTem = dic(dKey)
k = UBound(arrTem, 2) + 1
End If
'写入数组
ReDim Preserve arrTem(0 To 9, 0 To k)
arrTem(0, k) = k + 1
arrTem(1, k) = arr(i, Pxy(arr, "代理人", 2))
arrTem(2, k) = arr(i, Pxy(arr, "收付单号", 2))
arrTem(3, k) = arr(i, Pxy(arr, "不含税业务金额", 2))
arrTem(4, k) = arr(i, Pxy(arr, "系统手续费", 2))
arrTem(5, k) = arr(i, Pxy(arr, "系统手续费", 2))
arrTem(6, k) = arrTem(3, k) - arrTem(4, k)
arrTem(7, k) = arr(i, Pxy(arr, "收款人", 2))
arrTem(8, k) = arr(i, Pxy(arr, "开户行", 2))
arrTem(9, k) = arr(i, Pxy(arr, "收款人账号", 2))
dic(dKey) = arrTem '把数组存入字典
Next
For Each Key In dic.keys '循环字典的key
grandTotal = 0
Set ws = ThisWorkbook.Sheets("模板")
ws.Copy '复制模板到新的工作簿
Set ws = ActiveSheet
With ws
.Name = Key '工作表名称
arrTem = dic(Key) '当前key的Item存入数组,它原来就是一个数组。
For i = 0 To UBound(arrTem, 2)
grandTotal = grandTotal + Round(CDbl(arrTem(6, i)), 2)
Next
fileName = Key & "(" & Format(grandTotal, "Standard") & ").xlsx" '保存的文件名
iRows = UBound(arrTem, 2) + 1 '记录的行数,判断要不要插入行
If iRows > 1 Then '如果多于1行,则插入行
.Rows("5:" & 5 + iRows - 2).Insert shift:=xlDown
End If
With .Range("A4").Resize(iRows, 10) '数据区域
.Columns(3).NumberFormatLocal = "@" '设置账号栏文本,下同
.Columns(10).NumberFormatLocal = "@"
'把数组写入工作表
.Cells(1, 1).Resize(UBound(arrTem, 2) + 1, 10) = _
Application.WorksheetFunction.Transpose(arrTem)
.Cells(iRows + 1, 4).Resize(1, 4) = _
"=sum(" & .Columns(4).Address(0, 0) & ")"
.Cells(1, 4).Resize(iRows + 1, 4).NumberFormatLocal = "_ * #,##0.00_ ;_ * -#,##0.00_ ;_ * ""-""??_ ;_ @_ "
End With
End With
If proType = "打印" Then
ws.PrintOut copies:=1
End If
Set wb = ActiveWorkbook
wb.SaveAs saveFolder & "\" & fileName
wb.Close
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Done!"
End Sub