|
代码如下。。。
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Set sh = Sheets("购买记录")
Set sht = Sheets("发放记录")
Set d = CreateObject("scripting.dictionary")
Set dic = CreateObject("scripting.dictionary")
Dim ssh As Worksheet
brr = sh.[a1].CurrentRegion
arr = sht.[a1].CurrentRegion
For i = 3 To UBound(arr)
If arr(i, 1) <> Empty Then
For j = 6 To UBound(arr, 2) Step 2
If arr(i, j) <> Empty Then
If Not d.exists(arr(i, j)) Then Set d(arr(i, j)) = CreateObject("scripting.dictionary")
s = arr(i, 1) & "|" & arr(i, 2) & "|" & arr(i, 3) & "|" & arr(i, 4) & "|" & arr(i, 5)
If Not d(arr(i, j)).exists(s) Then
d(arr(i, j))(s) = arr(i, j + 1)
Else
d(arr(i, j))(s) = d(arr(i, j))(s) + arr(i, j + 1)
End If
End If
Next
End If
Next
For i = 2 To UBound(brr)
If Not dic.exists(brr(i, 2)) Then Set dic(brr(i, 2)) = CreateObject("scripting.dictionary")
dic(brr(i, 2))(brr(i, 1)) = brr(i, 4)
Next
For Each k In dic.keys
n = 2
On Error Resume Next
Set ssh = Sheets(k)
On Error GoTo 0
If ssh Is Nothing Then
With Sheets.Add(after:=Sheets(Sheets.Count))
.Name = k
.[a1].Resize(, 9).Merge
.[a1] = k
.[a2].Resize(, 9) = [{"日期","ID","客户名称","产品名称","金额","摘要","购买礼品数量","发放礼品数量","库存礼品数量"}]
For Each kk In dic(k).keys
n = n + 1
.Cells(n, 1) = kk
.Cells(n, 6) = "购买"
.Cells(n, 7) = dic(k)(kk)
Next
For Each kkk In d(k).keys
Key = Split(kkk, "|")
If Key(0) > kk Then
n = n + 1
For i = 0 To 4
.Cells(n, i + 1) = Key(i)
Next
.Cells(n, 6) = "发放礼品"
.Cells(n, 8) = d(k)(kkk)
End If
Next
.Cells(3, 1).Resize(n, 9).Sort key1:=.Range("a3"), _
order1:=xlAscending, Header:=xlNo
For i = 3 To .Cells(.Rows.Count, 1).End(3).Row
If .Cells(i, 9) = Empty Then
If .Cells(i, 6) = "购买" Then
If i = 3 Then .Cells(i, 9) = .Cells(i, 7) Else .Cells(i, 9) = .Cells(i, 7) + .Cells(i - 1, 9)
Else
.Cells(i, 9) = .Cells(i - 1, 9) - .Cells(i, 8)
End If
End If
Next
With .[a1].CurrentRegion
.Borders.LineStyle = 1
.HorizontalAlignment = xlCenter
.Columns.AutoFit
End With
End With
Else
With ssh
n = .Cells(.Rows.Count, 1).End(3).Row
For Each kk In dic(k).keys
n = n + 1
.Cells(n, 1) = kk
.Cells(n, 6) = "购买"
.Cells(n, 7) = dic(k)(kk)
Next
For Each kkk In d(k).keys
Key = Split(kkk, "|")
If Key(0) > kk Then
n = n + 1
For i = 0 To 4
.Cells(n, i + 1) = Key(i)
Next
.Cells(n, 6) = "发放礼品"
.Cells(n, 8) = d(k)(kkk)
End If
Next
.Cells(3, 1).Resize(n, 9).Sort key1:=.Range("a3"), _
order1:=xlAscending, Header:=xlNo
For i = 3 To .Cells(.Rows.Count, 1).End(3).Row
If .Cells(i, 6) = "购买" Then
If i = 3 Then .Cells(i, 9) = .Cells(i, 7) Else .Cells(i, 9) = .Cells(i, 7) + .Cells(i - 1, 9)
Else
.Cells(i, 9) = .Cells(i - 1, 9) - .Cells(i, 8)
End If
Next
With .[a1].CurrentRegion
.Borders.LineStyle = 1
.HorizontalAlignment = xlCenter
.Columns.AutoFit
End With
End With
End If
Next
Set d = Nothing
Set dic = Nothing
Application.ScreenUpdating = True
Beep
End Sub
Private Sub CommandButton2_Click()
Application.DisplayAlerts = False
n = Sheets.Count
For i = n To 4 Step -1
Sheets(i).Delete
Next
Application.DisplayAlerts = True
Beep
End Sub
|
|