Macros

Get Breakdown of SUMIFS Formula

VBA: SUMIFS Breakdown

Sub SUMIFS_Breakdown()
'Note the following shorthand: f = "Function"; c = "Criteria"; l = "Loop"
Dim Cell As Range, Breakdown As New Collection
    
    Call TurnStuffOff
    Rtn = ActiveSheet.Name
    x0 = Selection.Column
    y0 = Selection.Row
    
    'Find the relevant number of sheets already providing a breakdown and number i accordingly for naming the new sheet.
    For Each Sheet In ActiveWorkbook.Sheets
        If Sheet.Name Like "Breakdown*" Then Sheet.Delete
    Next Sheet
    
    y1 = 6
    For Each Cell In Selection
        If Cell.Value = 0 Then GoTo Next_Cell
        If InStr(Cell.Formula, "SUMIF") = 0 Then GoTo Next_Cell
        If InStr(Cell.Formula, "[") = 0 Then GoTo Next_Cell
        cRef = "'" & Rtn & "'!" & Cell.Address(0, 0)
        Sheets.Add(Before:=ActiveSheet).Name = "Breakdown"
        Range("A1") = Sheets(Rtn).Range("A1").Value
        Range("A2") = "=Hyperlink(""#" & cRef & """,""Breakdown of " & cRef & """)"
        Range("A3") = Sheets(Rtn).Range("A3").Value
        fStart = 1
Restart:
        If InStr(fStart, Cell.Formula, "SUMIFS") <> 0 Then
            
            'Find the SUMIFS string.
            fStart = InStr(fStart, Cell.Formula, "SUMIFS") + 7
            bCount = 1
            For i = fStart To Len(Cell.Formula)
                If Mid(Cell.Formula, i, 1) = "(" Then
                    bCount = bCount + 1
                ElseIf Mid(Cell.Formula, i, 1) = ")" Then
                   bCount = bCount - 1
                End If
                If bCount = 0 Then
                    fEnd = i
                    Exit For
                End If
            Next i
            fString = Mid(Cell.Formula, fStart, fEnd - fStart)
            fStart = fEnd
            
            'Define the referenced range, but only proceed with table ranges.
            If InStr(fString, "[") Then fRange = Mid(fString, 1, InStr(fString, "[") - 1) ': Range(fRange & "[#Headers]").Copy Cells(y1, 1)
            Set xSh = ThisWorkbook.Sheets(Range(fRange).Parent.Name): xSh.ListObjects(fRange).AutoFilter.ShowAllData
            
            'On Error GoTo -1: On Error GoTo Actioned
            lStart = InStr(fString, ",")
            i = 0
            Do Until lStart > Len(fString)
                Ary = vbNo
                'Find filters and place these into the criteria range.
                cRange = Mid(fString, InStr(lStart, fString, "[") + 1, InStr(lStart, fString, "]") - InStr(lStart, fString, "[") - 1)
                x1 = x1 + 1
                lStart = lStart + Len(fRange & cRange) + 4
                Cells(y1, x1) = cRange
IsArray:        If InStr(lStart, fString, ",") <> 0 Then cDetail = Mid(fString, lStart, InStr(lStart, fString, ",") - lStart) Else cDetail = Mid(fString, lStart, Len(fString) - lStart + 1)
                lStart = lStart + Len(cDetail)
                If InStr(cDetail, "{") Then Ary = vbYes
                If InStr(cDetail, "}") Then Ary = "EndA"
                If cDetail Like "*!*" Then cDetail = Range(cDetail).Value
                If InStr(cDetail, "@") > 0 Then
                    x = Sheets(Rtn).Cells.Find(Replace(Replace(Replace(cDetail, "@", ""), "[", ""), "]", "")).Column
                    cDetail = Sheets(Rtn).Cells(y0, x).Value
                    x = ""
                    GoTo Plant
                End If
                If InStr(cDetail, """") = 0 Then cDetail = Range(Rtn & "!" & cDetail).Value
                If InStr(cDetail, """&") Or InStr(cDetail, "&""") Then
                    x = Mid(cDetail, InStr(cDetail, "&") + 1, Len(cDetail) - InStr(cDetail, "&") + 1)
                    If InStr(x, "&") > 0 Then x = Left(x, InStr(x, "&"))
                End If
                cDetail = Replace(Replace(Replace(Replace(Replace(cDetail, "&""", ""), """&", ""), """", ""), "{", ""), "}", "")
                If x <> "" And IsNumeric(x) = False Then cDetail = Replace(cDetail, x, CLng(Range(x).Value)) 'Replace the named range within cDetail with the value of that range.
                If InStr(cDetail, "/") Then cDetail = DateValue(cDetail)
Plant:          If x1 = 1 Then
                    Cells(y1 + Application.CountA(Columns(x1)) - 3, x1).Value = cDetail
                Else
                    Cells(y1 + Application.CountA(Columns(x1)), x1).Value = cDetail
                End If
                If Ary = vbYes Then lStart = lStart + 1: GoTo IsArray
            Loop
            
            Set cRg = Cells(y1, 1).CurrentRegion
            If cRg.Rows.Count > 2 Then
                For i = 3 To cRg.Rows.Count
                    For Each Rng In cRg.Rows(i).Cells
                        If Rng = "" Then Rng.FillDown
                    Next Rng
                Next i
            End If
            y = cRg.Rows.Count + y1 + 1
            Range(fRange & "[#All]").Copy
            Cells(y, 1).PasteSpecial xlPasteAll: Cells(y, 1).PasteSpecial xlPasteColumnWidths
            On Error GoTo -1: On Error Resume Next
            y2 = Range("A1").SpecialCells(xlCellTypeLastCell).Row + 2
            Cells(y, 1).CurrentRegion.AdvancedFilter xlFilterInPlace, cRg, Cells(y + 1, 1)
            Cells(y, 1).CurrentRegion.SpecialCells(xlCellTypeVisible).Copy Cells(y2, 1)
            ActiveSheet.ShowAllData
            Rows(y1 & ":" & y2 - 1).EntireRow.Delete
            xAmnt = Cells.Find("Amount", LookAt:=xlWhole).Column: xBlnc = Cells.Find("Balance").Column: xHypr = Cells.Find("Hyperlink").Column
            Columns(xHypr).Delete: Columns(xBlnc).Delete
            If Cells(y1, 1).CurrentRegion.Rows.Count <> 1 Then
                y1 = y1 + 1: y2 = Cells(y1, 1).End(xlDown).Row
                Cells(y2 + 2, xAmnt) = "=SUBTOTAL(109," & Cells(y1, xAmnt).Address(0, 0) & ":" & Cells(y2 + 1, xAmnt).Address(0, 0) & ")"
                Range(Cells(y1, xAmnt), Cells(y2 + 2, xAmnt)).NumberFormat = "_-* #,##0.00_);_-* (#,##0.00);_-* ""-""??_);_-@_)"
                Rows(y2 + 1).RowHeight = 6: Cells(y2 + 2, xAmnt).Font.Bold = True
                y1 = y2 + 3
            End If
            GoTo Restart
            
        ElseIf InStr(fStart, Cell.Formula, "SUMIF") <> 0 Then
            
            'Find the SUMIF string.
            fStart = InStr(fStart, Cell.Formula, "SUMIF") + 6
            bCount = 1
            For i = fStart To Len(Cell.Formula)
                If Mid(Cell.Formula, i, 1) = "(" Then
                    bCount = bCount + 1
                ElseIf Mid(Cell.Formula, i, 1) = ")" Then
                   bCount = bCount - 1
                End If
                If bCount = 0 Then
                    fEnd = i
                    Exit For
                End If
            Next i
            fString = Mid(Cell.Formula, fStart, fEnd - fStart)
            fStart = fEnd
            
            'Define the referenced range, but only proceed with table ranges.
            If InStr(fString, "[") Then fRange = Mid(fString, 1, InStr(fString, "[") - 1): Range(fRange & "[#Headers]").Copy Cells(y1, 1)
            
            On Error GoTo -1: On Error GoTo Actioned
            
                'Find filter and place these into the criteria range.
                t1 = InStr(fString, ",")
                t2 = InStr(t1 + 1, fString, ",")
                
                cRange = Mid(fString, InStr(fString, "[") + 1, InStr(fString, "]") - InStr(fString, "[") - 1)
                cDetail = Mid(fString, t1 + 1, t2 - t1 - 1)
                
                If cDetail Like "*!*" Then cDetail = Range(cDetail).Value
                If InStr(cDetail, """") = 0 Then cDetail = Range(Rtn & "!" & cDetail).Value
                If InStr(cDetail, "&") > 0 Then
                    x = Mid(cDetail, InStr(cDetail, "&") + 1, Len(cDetail) - InStr(cDetail, "&") + 1)
                    If InStr(x, "&") > 0 Then x = Left(x, InStr(x, "&"))
                End If
                cDetail = Replace(Replace(Replace(cDetail, "&""", ""), """&", ""), """", "")
                If x <> "" Then cDetail = Replace(cDetail, x, Range(x).Formula)
                Cells(y1 + 1, Rows(6).Find(cRange, LookAt:=xlWhole).Column) = cDetail
            
            Set cRg = Cells(y1, 1).CurrentRegion
            y = Cells(y1, 1).CurrentRegion.Rows.Count + y1 + 1
            Range(fRange & "[#All]").Copy Cells(y, 1)
            On Error GoTo -1: On Error Resume Next
            y2 = Range("A1").SpecialCells(xlCellTypeLastCell).Row + 2
            Cells(y, 1).CurrentRegion.AdvancedFilter xlFilterInPlace, cRg, Cells(y + 1, 1)
            Cells(y, 1).CurrentRegion.SpecialCells(xlCellTypeVisible).Copy Cells(y2, 1)
            ActiveSheet.ShowAllData
            Rows(y1 & ":" & y2 - 1).EntireRow.Delete
            xAmnt = Cells.Find("Amount", LookAt:=xlWhole).Column: xBlnc = Cells.Find("Balance").Column: xHypr = Cells.Find("Hyperlink").Column
            Columns(xHypr).Delete: Columns(xBlnc).Delete
            If Cells(y1, 1).CurrentRegion.Rows.Count <> 1 Then
                y1 = y1 + 1: y2 = Cells(y1, 1).End(xlDown).Row
                Cells(y2 + 2, xAmnt) = "=SUBTOTAL(109," & Cells(y1, xAmnt).Address(0, 0) & ":" & Cells(y2 + 1, xAmnt).Address(0, 0) & ")"
                Range(Cells(y1, xAmnt), Cells(y2 + 2, xAmnt)).NumberFormat = "_-* #,##0.00_);_-* (#,##0.00);_-* ""-""??_);_-@_)"
                Rows(y2 + 1).RowHeight = 6: Cells(y2 + 2, xAmnt).Font.Bold = True
                y1 = y2 + 3
            End If
            GoTo Restart
        End If
Actioned:
        Actioned = vbYes
Next_Cell:
    Next Cell
    
    For Each Qy In ActiveWorkbook.Queries
        If Not Qy.Name Like "*_Cash" Then Qy.Delete
    Next Qy
    
    If Actioned = vbYes Then Call Std_Lead
    If Actioned <> vbYes Then MsgBox "This macro should only be run on cells containing a SUMIF(S) function that reference a tabular range.  None of these cells fit this criteria.", vbInformation + vbOKOnly, "Nothing happened..."
    Call TurnStuffOn
End Sub