+ Reply to Thread
Results 1 to 24 of 24

Count distinct values that correspond to a criteria

Hybrid View

  1. #1
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Count distinct values that correspond to a criteria

    Hi,

    I have a list of Customer and Items they have ordered.

    I have this code that counts how many orders have been placed for 2 specific items (TBA and 8IM) and places the value in worksheet List cell A1:

    Sub CountItems()
    Dim wsd As Worksheet, wsc As Worksheet
    Dim Lastrow As Long, i As Long, J As Long
    Dim Cell As Range
    
    Set wsc = Sheets("List")
    Set wsd = Sheets("Jan")
    
    i = 0
    
    Application.ScreenUpdating = False
    
    With wsd
        Lastrow = .Range("B" & Rows.Count).End(xlUp).Row
        For Each Cell In .Range("B2:B" & Lastrow)
            If Cell = "TBA" Or Cell = "8IM" Then
    i = i + 1
            End If
        Next Cell
    End With
     
    With wsc
        .Range("A1").Value = i
    
    End With
    
    Application.ScreenUpdating = True
    
    End Sub
    I would need some suggestions how to amend this code to count how many Customers have ordered either item TBA or item 8IM. If a Customer ordered at least once any of these items it has to be counted as 1.

    Thanks,
    Eduard
    Attached Files Attached Files

  2. #2
    Forum Expert
    Join Date
    03-28-2012
    Location
    TBA
    MS-Off Ver
    Office 365
    Posts
    12,454

    Re: Count distinct values that correspond to a criteria

    You do not need a code for this. Pivot table is much more flexible

  3. #3
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Re: Count distinct values that correspond to a criteria

    Thanks for advice AB33. I will use this figure in other reports and need to be able to get it quickly. So would prefer to do it with macro if possible.
    Last edited by Eduard; 04-19-2013 at 10:22 AM.

  4. #4
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Re: Count distinct values that correspond to a criteria

    Anyone there who can help, please? Let me know if I have to clarify something. Thanks.

  5. #5
    Registered User
    Join Date
    04-21-2013
    Location
    france
    MS-Off Ver
    Excel 2003
    Posts
    3

    Re: Count distinct values that correspond to a criteria

    Hello!

    Why not =CountIfI(B2:B9376;"TBA")+CounttIf(B2:B9376;"8IM")

    JB

  6. #6
    Registered User
    Join Date
    02-28-2010
    Location
    India
    MS-Off Ver
    Excel 2003
    Posts
    18

    Re: Count distinct values that correspond to a criteria

    Sub CountItems()
    Dim wsd As Worksheet, wsc As Worksheet
    Dim Lastrow As Long, i As Long, J As Long
    Dim Cell As Range

    Set wsc = Sheets("List")
    Set wsd = Sheets("Jan")

    i = 0

    Application.ScreenUpdating = False

    With wsd
    Lastrow = .Range("B" & Rows.Count).End(xlUp).Row
    For Each Cell In .Range("B2:B" & Lastrow)
    If Cell = "TBA" Then
    i = i + 1
    ElseIf Cell = "8IM" Then
    J = J + 1
    End If
    Next Cell
    End With

    With wsc
    .Range("A1").Value = "TBA"
    .Range("A2").Value = "8IM"
    .Range("B1").Value = i
    .Range("B2").Value = J

    End With

    Application.ScreenUpdating = True

    End Sub

  7. #7
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Re: Count distinct values that correspond to a criteria

    Thanks sujitshukla, but this will not work. This code will just return the number of orders for each item TBA and 8IM. It does not calculate how many customers ordered these item. You may have 1 customer ordering more than once the same item. That has to count as 1 and not for each time he placed the order.

  8. #8
    Forum Expert
    Join Date
    12-14-2012
    Location
    London England
    MS-Off Ver
    MS 365 Office Suite.
    Posts
    8,448

    Re: Count distinct values that correspond to a criteria

    Hi edward

    I think that the easiest way to do this is to use a select function to select all cells with TBA and 8IM, this may have to be done separately.

    Then add the customername to a collection such that duplicates are eliminated.

    15 lines of code should do it.

    Bear with me............

  9. #9
    Registered User
    Join Date
    04-21-2013
    Location
    france
    MS-Off Ver
    Excel 2003
    Posts
    3

    Re: Count distinct values that correspond to a criteria

    See pgm

    Numbers differents items for each customer

    In D2: 0101686500
    In E2:
    =COUNT(1/FREQUENCY(IF(customer=D2,MATCH(items,items,0)),ROW(INDIRECT("1:"&ROWS(items)))))
    Valid with upper+ctrl+Enter

    JB
    http://boisgontierjacques.free.fr
    Attached Files Attached Files
    Last edited by boisgontier; 04-21-2013 at 12:54 PM.

  10. #10
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Re: Count distinct values that correspond to a criteria

    Thanks boisgontier. I have tried using array formulas, but that works very slow. I have 11 other worksheets and it takes minutes to calculate all the values.

  11. #11
    Forum Expert
    Join Date
    12-14-2012
    Location
    London England
    MS-Off Ver
    MS 365 Office Suite.
    Posts
    8,448

    Re: Count distinct values that correspond to a criteria

    Ok this is One Method.

    Read all the values into an array and check each row.

    I will re-write this to use excel sort to reduce the length of the loop.
    Attached Files Attached Files

  12. #12
    Forum Guru MarvinP's Avatar
    Join Date
    07-23-2010
    Location
    Woodinville, WA
    MS-Off Ver
    Office 365
    Posts
    16,355

    Re: Count distinct values that correspond to a criteria

    Look at the attached that uses a Pivot Table, is VERY fast and will give you what you want. I know you want VBA but why? If a built-in function or formula is available, why not use it as they are ALWAYS faster than VBA or Array formulas.
    Attached Files Attached Files
    One test is worth a thousand opinions.
    Click the * Add Reputation below to say thanks.

  13. #13
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Count distinct values that correspond to a criteria

    Quote Originally Posted by MarvinP View Post
    If a built-in function or formula is available, why not use it as they are ALWAYS faster than VBA or Array formulas.
    Not always.

    try
    Sub CountItems()
        Dim a, i As Long, n As Long
        a = Sheets("jan").Cells(1).CurrentRegion.Value
        With CreateObject("Scripting.Dictionary")
            a(1, 2) = "Count": n = 1
            For i = 2 To UBound(a, 1)
                If (a(i, 2) = "TBA") + (a(i, 2) = "8IM") Then
                    If Not .exists(a(i, 1)) Then
                        n = n + 1: .Item(a(i, 1)) = n
                        a(n, 1) = a(i, 1): a(n, 2) = 1
                    Else
                        a(.Item(a(i, 1)), 2) = a(.Item(a(i, 1)), 2) + 1
                    End If
                End If
            Next
        End With
        Sheets("list").Cells(1).Resize(n, 2).Value = a
    End Sub

  14. #14
    Forum Guru MarvinP's Avatar
    Join Date
    07-23-2010
    Location
    Woodinville, WA
    MS-Off Ver
    Office 365
    Posts
    16,355

    Re: Count distinct values that correspond to a criteria

    Did I see the answer for the question after running your Scripting.Dictionary? How many customers had TBA or 8IM?

  15. #15
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Re: Count distinct values that correspond to a criteria

    Hi MarvinP,

    I would need to have 12 pivot tables since I have 12 worksheets with data, i.e. one for each month. Every time a new worksheet is added the user will have to create the pivot table and they don't necessarily know how to do that. Clicking a button with a macro would be more practical and user-friendly.

    Eduard

  16. #16
    Forum Guru MarvinP's Avatar
    Join Date
    07-23-2010
    Location
    Woodinville, WA
    MS-Off Ver
    Office 365
    Posts
    16,355

    Re: Count distinct values that correspond to a criteria

    Hey -

    How about a macro that creates a pivot table based on the active sheet that is being looked at? Are there some columns that I can use for temporary work?

    Run Macro 2 on any sheet and it will give the correct answer for that sheet. See the attached with Macro 2 included.
    Attached Files Attached Files

  17. #17
    Forum Expert
    Join Date
    12-14-2012
    Location
    London England
    MS-Off Ver
    MS 365 Office Suite.
    Posts
    8,448

    Re: Count distinct values that correspond to a criteria

    This is a faster method than my previous post
    Attached Files Attached Files

  18. #18
    Forum Expert JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    The grid, I got in!
    MS-Off Ver
    Excel 2010/13
    Posts
    1,696

    Re: Count distinct values that correspond to a criteria

    Try this,

    This will count only the customers who bought either of those items in each sheet.

    Sub countS()
      
      Dim i As Long
      Dim ws As Worksheet 
      Dim a
      Dim j
      Dim jj As Long
      Dim d
            
             Set d = CreateObject("Scripting.dictionary")
          For Each ws In ActiveWorkbook.Sheets
             If ws.Name <> "List" Then
                a = ws.Range("A2:B" & ws.Cells(ws.Rows.Count, 2).End(xlUp).Row)
                  For j = LBound(a) To UBound(a)
                     If a(j, 2) = "TBA" Or Cell = "8IM" Then
                        If Not d.exists(Trim(a(j, 1))) Then
                            d.Add Trim(a(j, 1)), Trim(a(j, 1)): jj = jj + 1
                        End If
                     End If
                  Next
             End If
          Next
            MsgBox "There were " & jj & " customers who bought items TBA and 8IM"
    End Sub
    Attached Files Attached Files
    Be fore warned, I regularly post drunk. So don't take offence (too much) to what I say.
    I am the real 'Napster'
    The Grid. A digital frontier. I tried to picture clusters of information as they moved through the computer. What did they look like? Ships? motorcycles? Were the circuits like freeways? I kept dreaming of a world I thought I'd never see. And then, one day...

    If you receive help please give thanks. Click the * in the bottom left hand corner.

    snb's VBA Help Files

  19. #19
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Count distinct values that correspond to a criteria

    If it is only a count then
    Sub CountItems()
        Dim a, i As Long
        a = Sheets("jan").Cells(1).CurrentRegion.Value
        With CreateObject("Scripting.Dictionary")
             For i = 2 To UBound(a, 1)
                If (a(i, 2) = "TBA") + (a(i, 2) = "8IM") Then .Item(a(i, 1)) = Empty
            Next
            Sheets("list").Cells(1).Value  = .Count
        End With
    End Sub
    Last edited by jindon; 04-22-2013 at 01:34 AM. Reason: Cleaned the code.

  20. #20
    Registered User
    Join Date
    04-21-2013
    Location
    france
    MS-Off Ver
    Excel 2003
    Posts
    3

    Re: Count distinct values that correspond to a criteria

    With UDF

    Function ItemsDifferentsCritere(champ, champcritere, critere)
      Set MonDico = CreateObject("Scripting.Dictionary")
      a = champ
      b = champcritere
      For i = 1 To champ.Count
        If b(i, 1) = critere And a(i, 1) <> "" Then
           temp = a(i, 1)
           MonDico(temp) = temp
        End If
      Next i
      ItemsDifferentsCritere = MonDico.Count
    End Function
    JB
    Attached Files Attached Files

  21. #21
    Forum Expert
    Join Date
    10-06-2008
    Location
    Canada
    MS-Off Ver
    2007 / 2013
    Posts
    5,697

    Re: Count distinct values that correspond to a criteria

    @JapanDave
    Should this
    If a(j, 2) = "TBA" Or Cell = "8IM" Then
    be?
    If a(j, 2) = "TBA" Or a(j, 2) = "8IM" Then

  22. #22
    Forum Expert JapanDave's Avatar
    Join Date
    06-10-2008
    Location
    The grid, I got in!
    MS-Off Ver
    Excel 2010/13
    Posts
    1,696

    Re: Count distinct values that correspond to a criteria

    Ouch, yes it should be this.
    If a(j, 2) = "TBA" Or a(j, 2) = "8IM" Then

  23. #23
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Re: Count distinct values that correspond to a criteria

    Hi MarvinP,

    Your macro does not seem to work. Gives an error in this line:

        ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
            ActiveSheet.Name & "!R1C1:R" & LastRow & "C2", Version:=xlPivotTableVersion15).CreatePivotTable _
            TableDestination:=ActiveSheet.Name & "!R3C4", TableName:="PivotTable3", DefaultVersion:= _
            xlPivotTableVersion15

  24. #24
    Registered User
    Join Date
    08-30-2005
    Posts
    67

    Re: Count distinct values that correspond to a criteria

    Thanks JapanDave. This is exactly what I was looking for.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1