Sub Test()
Dim cell As Range, a, b, c, d, i As Long, j As Long, k As Long, str1 As String, str2 As String, strNumFormat As String, total As Single, v1, v2, z1 As New Collection, z2 As New Collection, z3 As New Collection
Sheets.Add after:=Sheets(Sheets.Count)
Set cell = ActiveSheet.Range("A1")
With Sheets("Sheet1").Range("A1").CurrentRegion
a = .Value
strNumFormat = .Cells(2, 9).NumberFormat
For i = 2 To UBound(a, 1)
str1 = a(i, 2) & Chr$(2) & a(i, 3)
str2 = a(i, 3) & Chr$(2) & a(i, 2)
On Error Resume Next
v1 = z1(str1)
If Err.Number = 0 Then v1(1).Add i: GoTo skipper
Err.Clear
v1 = z1(str2)
If Err.Number = 0 Then v1(2).Add i: GoTo skipper
Err.Clear
z1.Add Key:=str1, Item:=Array(str1, New Collection, New Collection)
z1(str1)(1).Add i
skipper:
On Error GoTo 0
Next i
k = 1
ReDim d(1 To z1.Count + 1, 1 To 4)
d(1, 1) = "Date"
d(1, 2) = "Pay From"
d(1, 3) = "Pay to"
d(1, 4) = "Amount"
For Each v1 In z1
total = 0
i = 0
c = Split(v1(0), Chr$(2))
For Each v2 In v1(1): total = total - a(v2, 9): Next v2
For Each v2 In v1(2): total = total + a(v2, 9): Next v2
If total >= 0 Then
Set z2 = v1(1)
Set z3 = v1(2)
Else
Set z2 = v1(2)
Set z3 = v1(1)
total = Abs(total)
v2 = c(0): c(0) = c(1): c(1) = v2
End If
ReDim b(1 To z2.Count + z3.Count + 2, 1 To UBound(a, 2))
For Each v2 In z2
i = i + 1
For j = 1 To UBound(a, 2)
b(i, j) = a(v2, j)
Next j
Next v2
For Each v2 In z3
i = i + 1
For j = 1 To UBound(a, 2)
b(i, j) = a(v2, j)
Next j
Next v2
i = i + 2
b(i, 1) = "According to above"
b(i, 2) = "Invoice"
b(i, 3) = c(0)
b(i, 4) = "to Pay"
b(i, 5) = c(1)
b(i, 6) = ">>>>>>>>>>>>>>>>>>>>'"
b(i, 9) = total
k = k + 1
d(k, 1) = b(1, 1)
d(k, 2) = c(0)
d(k, 3) = c(1)
d(k, 4) = total
.Rows(1).Copy cell
cell.Offset(1).Resize(UBound(b, 1), UBound(b, 2)).Value = b
Set cell = cell.Offset(UBound(b, 1) + 3)
Next v1
End With
With cell.Parent.UsedRange
.EntireColumn.AutoFit
.Columns("H:I").NumberFormat = strNumFormat
End With
With cell.Parent.Range("L1").Resize(UBound(d, 1), UBound(d, 2))
.Value = d
.Borders.Weight = xlThin
.EntireColumn.AutoFit
.Columns(4).NumberFormat = strNumFormat
End With
End Sub
Bookmarks