Option Explicit
Sub demo_vba()
Dim a, Hdrs, totals
Dim s As Long, i As Long, j As Long, n As Long, lc As Long, lr As Long, ws_count As Long
Dim cd As Long, ct As Long, ns As Long, fd As Long, td As Long
Dim ws As Worksheet
Dim key As String
Dim dict As Object
Application.ScreenUpdating = False
Set dict = CreateObject("Scripting.Dictionary")
If Range("fDate") = "" Then fd = DateValue("01/01/2020") Else fd = Range("fDate") ' Set Default date if no date entered
If Range("tDate") = "" Then td = DateValue("31/12/2099") Else td = Range("tDate") ' Set Default date if no date entered
ws_count = ActiveWorkbook.Worksheets.Count ' Count of sheets
ReDim b(1 To 100, 1 To ws_count + 1)
ReDim Hdrs(1 To 1, 1 To ws_count + 1)
ReDim Total(1 To 1, 1 To ws_count - 1)
Hdrs(1, 1) = "ITEM": Hdrs(1, 2) = "DESCRIBE": ns = 0 ' Headings
With dict
For s = 1 To ws_count
If Worksheets(s).Name <> "RESULT" Then
Set ws = Worksheets(s)
ns = ns + 1
Hdrs(1, ns + 2) = Worksheets(s).Name ' Add sheet name ("TX Type") to headings
With ws
lc = .Cells(1, Columns.Count).End(xlToLeft).Column ' Last column
lr = .Cells(Rows.Count, lc).End(xlUp).Row ' Last row
a = .UsedRange ' Input sheet data
For j = 1 To UBound(a, 2)
If a(1, j) = "DETAILS" Then ' "DETAILS" column number
cd = j
Else
If a(1, j) = "TOTAL" Then ct = j ' "TOTAL" column number
End If
Next j
For i = 2 To UBound(a, 1)
If a(i, cd) <> "" Then
key = Mid(a(i, cd), 1, InStr(1, a(i, cd), "NO") - 2) ' Set "KEY" (text prior to "NO" in "DETAILS" column)
If Not dict.exists(key) Then
n = n + 1
dict.Add key, n
b(n, 1) = n: b(n, 2) = key ' Add ITEM number plus KEY to output array
End If
If a(i, cd - 1) >= fd And a(i, cd - 1) <= td Then ' Check if in date range ....
b(dict.Item(key), s + 2) = b(dict.Item(key), s + 2) + a(i, ct) ' Accumulate total for this "sub-TX Type""
Total(1, s) = Total(1, s) + a(i, ct) ' "TX Type" total ("PURCHASE","SALES" etc)
End If
End If
Next i
End With
End If
Next s
End With
For i = 1 To n
For j = 3 To ws_count + 1
If b(i, j) = "" Then b(i, j) = 0
Next j
Next i
With Sheets("RESULT")
.UsedRange.Offset(6).Clear
.[A7].Resize(1, ws_count + 1) = Hdrs: .[A7].Resize(1, ws_count + 1).Font.Bold = True
.[A7].Resize(1, ws_count + 1).HorizontalAlignment = xlCenter
.[A8].Resize(n, ws_count + 1) = b
.Cells(n + 8, "A") = "TOTAL"
.Cells(n + 8, "C").Resize(1, ws_count - 1) = Total
.Cells(n + 8, "A").Resize(1, ws_count + 1).Font.Bold = True
.[A7].Resize(n + 2, ws_count + 1).Borders.Weight = 2
.[C8].Resize(n + 1, ws_count - 1).NumberFormat = "#,0.00;-#,0.00;-"
End With
Application.ScreenUpdating = True
End Sub
Bookmarks