Count number within slabs through excels function

2019-06-09 07:07发布

问题:

I want to count the amount between different value slabs. For Example

**Customer      Amount** 
A               100
B               300
A               500
C               700
D               900
E               1100
F               1300
G               1500
H               1700
I               1900

Desired result

**Solutions          Count**
Between 100-500         2
Between 500-1000        3
Between 1000-1500       3
Between 1500-2000       2

i tried it trough countif formula but it include a lot of efforts when there is huge data and lots of amount slabs are included

回答1:

If it can help, I have a peace of code which generates the formula for the "slabs", and calculate the number of occurrences within.

Say you have your values in column C (beware for C only to contain numbers; to be sure you can also make it $C$1:$C$1000$or so), and the plots of your slabs start with 0 in $D$14. Output in column G (and debug in columns E - F)

With Function MakeR1C1:

Function MakeR1C1(A1Formula As String) As String

MakeR1C1 = Application.ConvertFormula( _
    Formula:=A1Formula, _
    fromReferenceStyle:=xlA1, _
    toReferenceStyle:=xlR1C1, _
    ToAbsolute:=xlAbsolute)

End Function

Then you can work with the below (I made only 10 slabs):

Public Sub it()
    On Error GoTo ErrorTrap
    Dim wkRange As Range
    Dim inputRange As String
    Dim argFormula As String
    this_workbook = "MyWBook.xlsm"
    mySheet = "MySheet"
    ' Important: to make it work it is necessary to use WB+Sheet reference
    inputRange = "[" & this_workbook & "]" & mySheet & "!$C:$C"
    inputRange = MakeR1C1(inputRange)

    Set wkRange = ThisWorkbook.Sheets(mySheet).Range("D15:D25")
    ' D14: starting plot
    For Each C In wkRange
        upBound = C.Value
        lowBound = C.Offset(-1, 0).Value
        argFormula = "COUNT(" & inputRange & ") " & _
                 " - COUNTIF(" & inputRange & " ,"">" & upBound & """) " & _
                 " - COUNTIF(" & inputRange & " ,""<=" & lowBound & """)"
        C.Offset(0, 1).Value = argFormula
        C.Offset(0, 2).Value = "between " & lowBound & " and " & upBound
        C.Offset(0, 3).FormulaR1C1 = "=" & argFormula
    Next

Exit Sub
ErrorTrap:
    Beep
    MsgBox "FAILED" & Chr(13) & _
                    "arg: " & argFormula & Chr(13) & _
                    "Error number: " & Err & Chr(13) & _
                    Error(Err)
End Sub