Public Sub CompileDebtors()
Dim wb As Workbook, shtMonth As Worksheet, shtDebtor As Worksheet
Dim head As Range, heads As Range, debtors As Range, debtor As Range
Dim tDebtor As Range, tDebtorReceived As Range
Set wb = ThisWorkbook
Set shtDebtor = wb.Worksheets("Debtors")
Set tDebtor = shtDebtor.Range("A3:H" & shtDebtor.Rows.Count)
tDebtor.ClearContents
Set tDebtor = shtDebtor.Range("A3")
Set tDebtorReceived = shtDebtor.Range("E3")
For Each shtMonth In wb.Worksheets
If Not shtMonth Is shtDebtor Then
Set heads = shtMonth.Range("1:1").Find("Category", , xlValues, xlWhole)
If Not heads Is Nothing Then
Do
Set head = shtMonth.Range("1:1").FindNext(heads.Areas(heads.Areas.Count))
If InStr(heads.Address, head.Address) = 0 Then
Set heads = shtMonth.Range(heads.Address & "," & head.Address)
Else
Exit Do
End If
Loop
For Each head In heads.Areas
Set head = head.Resize(1 + Rows.CountLarge - head.Row, 1)
Set debtors = head.Find("Debtors*", , xlValues, xlWhole)
If Not debtors Is Nothing Then
Do
Set debtor = head.FindNext(debtors.Areas(debtors.Areas.Count))
If InStr(debtors.Address, debtor.Address) = 0 Then
Set debtors = shtMonth.Range(debtors.Address & "," & debtor.Address)
Else
Exit Do
End If
Loop
For Each debtor In debtors.Areas
Select Case debtor.Value
Case "Debtors"
tDebtor.Value = debtor.Offset(0, -1).Value
tDebtor.Offset(0, 1).Resize(1, 3) = debtor.Offset(0, 1).Resize(1, 3).Value
Set tDebtor = tDebtor.Offset(1, 0)
Case "Debtors Received"
tDebtorReceived.Value = debtor.Offset(0, -2).Value
tDebtorReceived.Offset(0, 1).Resize(1, 2) = debtor.Offset(0, 1).Resize(1, 2).Value
tDebtorReceived.Offset(0, 3) = debtor.Offset(0, 4).Value
Set tDebtorReceived = tDebtorReceived.Offset(1, 0)
End Select
Next
End If
Next
End If
End If
Next
If tDebtor.Row > tDebtorReceived.Row Then
Set tDebtorReceived = tDebtorReceived.Offset(tDebtor.Row - tDebtorReceived.Row)
Else
Set tDebtor = tDebtor.Offset(tDebtorReceived.Row - tDebtor.Row)
End If
If tDebtor.Row > 3 Then
Set tDebtor = tDebtor.Offset(0, 3)
Set tDebtorReceived = tDebtorReceived.Offset(0, 3)
tDebtor.Formula = "=SUM(" & tDebtor.Offset(3 - tDebtor.Row, 0).Address & ":" & tDebtor.Offset(-1, 0).Address & ")"
tDebtorReceived.Formula = "=SUM(" & tDebtorReceived.Offset(3 - tDebtorReceived.Row, 0).Address & ":" & tDebtorReceived.Offset(-1, 0).Address & ")"
End If
End Sub