Option Explicit
Sub demo()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim a, b, c, fuels, dept, fType, x, y
Dim lr As Long, i As Long, j As Long, n As Long, nmax As Long, nn(3) As Long, nx As Long
Dim vDate As Long
fuels = Array("Diesel", "Diesel to Petrol", "Petrol", "Filter", "Grease", "M. Oil", "Service")
Set ws1 = Sheets("Test")
Set ws2 = Sheets("Day total")
Set ws3 = Sheets("Define")
ReDim b(1 To 20, 1 To 29)
ReDim c(1 To 30, 1 To 5)
With ws1
a = .[A1].CurrentRegion
End With
With ws3
dept = .Range("C7:C20")
End With
With ws2
vDate = .Range("C2")
.[H6].Resize(30, 20).ClearContents
End With
For j = 0 To 2
fType = fuels(j) ' Type of fuel
nn(j) = 0
For i = 1 To UBound(dept, 1) ' Loop through Departments
x = Application.SumIfs(ws1.Range("N:N"), ws1.Range("C:C"), vDate, ws1.Range("I:I"), fType, ws1.Range("H:H"), dept(i, 1))
If x > 0 Then
nn(j) = nn(j) + 1: n = nn(j)
b(n, j * 5 + 6) = n: b(n, j * 5 + 7) = dept(i, 1): b(n, j * 5 + 8) = fType: b(n, j * 5 + 9) = x
If j = 0 Then ' If "Petrol" found the check for "Diesel to Petrol"
nn(3) = nn(3) + 1: n = nn(3)
b(n, j * 5 + 1) = n: b(n, j * 5 + 2) = dept(i, 1): b(n, j * 5 + 3) = fType: b(n, j * 5 + 4) = x
y = Application.SumIfs(ws1.Range("N:N"), ws1.Range("C:C"), vDate, ws1.Range("I:I"), fuels(1), ws1.Range("H:H"), dept(i, 1))
If y > 0 Then
nn(3) = nn(3) + 1: n = nn(3)
b(n, j * 5 + 1) = n: b(n, j * 5 + 2) = dept(i, 1): b(n, j * 5 + 3) = fuels(1): b(n, j * 5 + 4) = y
End If
End If
nx = nx + 1 ' Create Summary for main fuels
c(nx, 1) = nx: c(nx, 2) = dept(i, 1): c(nx, 3) = fType: c(nx, 4) = x
End If
Next i
nmax = Application.Max(nmax, n)
Next j
For j = 3 To 6 ' Create remainder of Summary
fType = fuels(j) ' Type of "Others"
For i = 1 To UBound(dept, 1) ' Loop through Departments
x = Application.SumIfs(ws1.Range("P:P"), ws1.Range("C:C"), vDate, ws1.Range("I:I"), fType, ws1.Range("H:H"), dept(i, 1))
If x > 0 Then
nx = nx + 1
c(nx, 1) = nx: c(nx, 2) = dept(i, 1): c(nx, 3) = fType: c(nx, 5) = x
End If
Next i
Next j
With ws2
.[H6].Resize(nmax, 19) = b
.[B6].Resize(nx, 5) = c
End With
End Sub
Bookmarks