+ Reply to Thread
Results 1 to 18 of 18

VBA Count Unique Values

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    VBA Count Unique Values

    Hi, I wonder whether someone may be able to help me please.

    Using an example I've discovered here: https://uk.answers.yahoo.com/questio...8105107AAt5dg4 I'm trying to put together a script which counts the unique values in column B, but assigns these to the unique values in column D.

    I must admit I don't entirely understand the original script in full, but I've managed to make some changes which you'll find in the attached a file, which I'm also hoping will perhaps illustrate what I'm trying to achieve a little better.

    • Please open the file where you'll be taken to the "In Flight Projects" sheet, then please
    • Click on the button,
    • You'll notice that from cell G3 the unique values from column D are listed, and in column H, the number of times that value appears in column D.

    What I'm trying to do is still keep the values in column G exactly the same, but rather than counting the values from column D, I want to count the unique values from column B.

    To show the results I'm looking to achieve and location on the sheet I've included a "Desired Outcome" sheet.

    I just wondered whether someone could possibly look at this please and offer some guidance on how I may achieve this.

    Many thanks and kind regards
    Attached Files Attached Files
    Last edited by hobbiton73; 03-30-2014 at 10:57 AM.

  2. #2
    Forum Expert nilem's Avatar
    Join Date
    10-22-2011
    Location
    Ufa, Russia
    MS-Off Ver
    2013
    Posts
    3,377

    Re: VBA Count Unique Values

    Hi hobbiton73,
    try
    Sub ertert()
    Dim x, i&, t()
    x = Range("B8:D" & Cells(Rows.Count, 2).End(xlUp).Row).Value
    Range("G2").CurrentRegion.ClearContents
    With CreateObject("Scripting.Dictionary")
        .CompareMode = 1
        For i = 1 To UBound(x)
            If Not .Exists(x(i, 3)) Then
                .Item(x(i, 3)) = Array(x(i, 3), 1, "~" & x(i, 1) & "~")
            Else
                t() = .Item(x(i, 3))
                If InStr(t(2), "~" & x(i, 1) & "~") = 0 Then
                    t(1) = t(1) + 1
                    t(2) = t(2) & x(i, 1) & "~"
                    .Item(x(i, 3)) = t()
                End If
            End If
        Next i
        Range("G2:H2").Resize(.Count) = Application.Index(.items, 0, 0)
    End With
    End Sub

  3. #3
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @nilem, thank you very much for taking the time to reply to my post and for the solution which works great.

    May I just ask a couple of more things please.

    • Would it be possible to paste the results on the "Desired Outcome" sheet in columns B and C starting at row 8 please, and
    • Could you possibly insert some notes into the code please so I can learn from this.

    Many thanks and kind regards

  4. #4
    Forum Expert nilem's Avatar
    Join Date
    10-22-2011
    Location
    Ufa, Russia
    MS-Off Ver
    2013
    Posts
    3,377

    Re: VBA Count Unique Values

    try again
    Sub ertert()
    Dim x, i&, t()
    With Sheets("In Flight Projects")
        x = .Range("B8:D" & .Cells(Rows.Count, 2).End(xlUp).Row).Value
    End With
    With Sheets("Desired Outcome")
        .Range("B8:C" & .Cells(Rows.Count, 2).End(xlUp).Row + 1).ClearContents
    End With
    With CreateObject("Scripting.Dictionary")
        .CompareMode = 1
        For i = 1 To UBound(x)
            If Not .Exists(x(i, 3)) Then
                .Item(x(i, 3)) = Array(x(i, 3), 1, "~" & x(i, 1) & "~")
            Else
                t() = .Item(x(i, 3))
                If InStr(t(2), "~" & x(i, 1) & "~") = 0 Then
                    t(1) = t(1) + 1
                    t(2) = t(2) & x(i, 1) & "~"
                    .Item(x(i, 3)) = t()
                End If
            End If
        Next i
        Sheets("Desired Outcome").Range("B8:C8").Resize(.Count) = Application.Index(.items, 0, 0)
    End With
    End Sub

  5. #5
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @nilem, I'm very sorry to, trouble you again, but I wonder if you may be able to help me with a problem I've come across when trying to implement the code in live environment.

    When I have a list of values in column B on the "In Flight Projects" which currently runs to 160 rows, I recieve the following error:

    'Run time error '13': Type mismatch' and highlights this line as the cause :
    Sheets("Slide 1").Range("B8:C8").Resize(.Count) = Application.Index(.items, 0, 0)

    I've tried to narrow down the cause, and I can't dertermine whether it's the number of characters per value or the total number of characters within the column.

    Have you any ideas please where I may be going wrong?

    Many thanks and kind regards
    Last edited by hobbiton73; 03-31-2014 at 05:12 AM.

  6. #6
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @nilem, thank you very much for taking the time to come back to me with this, it's works great.

    Could I possibly trouble you to include some notes the code please, so I can learn how this works.

    Many thanks and kind regards

  7. #7
    Forum Expert nilem's Avatar
    Join Date
    10-22-2011
    Location
    Ufa, Russia
    MS-Off Ver
    2013
    Posts
    3,377

    Re: VBA Count Unique Values

    Could you show your file in which an error occurs

  8. #8
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @nilem, thank you very much for taking the time to come back to me with this, I really appreciate it

    Unfortunately I'm unable to post the file because of the confidential information contained within it. I know this isn't particularly helpful.

    I've perfomed more tests, but to be honest I really can't determine why it's happening

    Many thanks and kind regards

  9. #9
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @nilem, thank you very much for your continued help with this.

    I've sent you a private message but I'm not sure whether it's work.

    Just in case, I've managed to put together a file which illustrates the error.

    • If you could please open the file and click the button you will see the error
    • However, if you then change the values in column B on rows 11 and 12 to "Digitalisation", and then select the button again, the macro will work.

    I'm not sure whether it's a memory buffer or number of characters issue.

    For example if you reload the file and change the value in column B on the final role to "Universal" the macro will work.

    I hope this helps.

    Many thanks and kind regards
    Attached Files Attached Files

  10. #10
    Forum Expert nilem's Avatar
    Join Date
    10-22-2011
    Location
    Ufa, Russia
    MS-Off Ver
    2013
    Posts
    3,377

    Re: VBA Count Unique Values

    Here's your file. try again (I hope everything will turn out now )
    Sub ertert()
    Dim x, y(), i&, j&, t()
    With Sheets("In Flight Projects")
        x = .Range("B8:D" & .Cells(Rows.Count, 2).End(xlUp).Row).Value
    End With
    With Sheets("Desired Outcome")
        .Range("B8:C" & .Cells(Rows.Count, 2).End(xlUp).Row + 1).ClearContents
    End With
    ReDim y(1 To UBound(x), 1 To 2)
    With CreateObject("Scripting.Dictionary")
        .CompareMode = 1
        For i = 1 To UBound(x)
            If Not .Exists(x(i, 3)) Then
                j = j + 1
                .Item(x(i, 3)) = Array(j, "~" & x(i, 1) & "~")
                y(j, 1) = x(i, 3)
                y(j, 2) = 1
            Else
                t() = .Item(x(i, 3))
                If InStr(t(1), "~" & x(i, 1) & "~") = 0 Then
                    t(1) = t(1) & x(i, 1) & "~"
                    y(t(0), 2) = y(t(0), 2) + 1
                    .Item(x(i, 3)) = t()
                End If
            End If
        Next i
        Sheets("Desired Outcome").Range("B8:C8").Resize(j) = y()
        Sheets("Desired Outcome").Activate
    End With
    End Sub
    Attached Files Attached Files

  11. #11
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: VBA Count Unique Values

    Hello hobbiton73,

    Here is another method of counting and listing the unique values. This method is not sensitive to punctuation characters and also ignores blank rows. This macro has been added to the attached workbook.

    Sub CountUniques()
    
        Dim Field   As String
        Dim oConn   As Object
        Dim oRS     As Object
        Dim Rng     As Range
        Dim Table   As String
        Dim Unique  As Variant
        Dim Uniques As Variant
        Dim Wks     As Worksheet
        
            Set Wks = Worksheets("In Flight Projects")
            
            Set Rng = Wks.Range("B7").CurrentRegion
            
            Field = "Project Name"
            
                Table = "[" & Wks.Name & "$" & Rng.Address(False, False) & "]"
                Field = "[" & Field & "]"
                
                Set oConn = CreateObject("ADODB.Connection")
                    oConn.Open "Provider=MSDASQL;DSN=Excel Files;DBQ=" & ThisWorkbook.FullName & ";HDR=Yes';"
                
                Set oRS = CreateObject("ADODB.Recordset")
                    oRS.Open "SELECT DISTINCT " & Field & " FROM " & Table, oConn, 1, 1
                        Uniques = oRS.GetRows()
                    oRS.Close
                    
                With Worksheets("Desired OutCome")
                    .Range("B8", .Cells(Rows.Count, "C").End(xlUp)).ClearContents
                    
                    For Each Unique In Uniques
                        oRS.Open "SELECT COUNT(" & Field & ") FROM " & Table & " WHERE " & Field & "='" & Unique & "';", oConn, 1, 1
                            .Range("B8:C8").Offset(n, 0).Value = Array(Unique, oRS.Fields(0).Value)
                        oRS.Close
                        n = n + 1
                    Next Unique
                End With
                    
            oConn.Close
            
    End Sub
    Attached Files Attached Files
    Sincerely,
    Leith Ross

    Remember To Do the Following....

    1. Use code tags. Place [CODE] before the first line of code and [/CODE] after the last line of code.
    2. Thank those who have helped you by clicking the Star below the post.
    3. Please mark your post [SOLVED] if it has been answered satisfactorily.


    Old Scottish Proverb...
    Luathaid gu deanamh maille! (Rushing causes delays!)

  12. #12
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @Leith Ross, thank you very much for taking the time to reply to my post and for putting the code together.

    I've downloaded the file uyou kindly provide, but unfortunately, perhaps as you've been putting this together the values from column D have been overwritten.

    If you perhaps have a moment please, you'll see that the original file contained a value in this column, which I then wanted to use on the "Desired Outcome" sheet against the number of times there was a unique entry in column B.

    Many thanks and kind regards

  13. #13
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: VBA Count Unique Values

    Hello hobbiton73,

    It would appear that I failed to save my last change before I posted the workbook. Here is the revised macro and workbook.

    Revised Code
    Sub CountUniques()
    
        Dim Field   As String
        Dim oConn   As Object
        Dim oRS     As Object
        Dim Rng     As Range
        Dim Table   As String
        Dim Unique  As Variant
        Dim Uniques As Variant
        Dim Wks     As Worksheet
        
            Set Wks = Worksheets("In Flight Projects")
            
            Set Rng = Wks.Range("B7").CurrentRegion
            
            Field = "Project Name"
            
                Table = "[" & Wks.Name & "$" & Rng.Address(False, False) & "]"
                Field = "[" & Field & "]"
                
                Set oConn = CreateObject("ADODB.Connection")
                    oConn.Open "Provider=MSDASQL;DSN=Excel Files;DBQ=" & ThisWorkbook.FullName & ";HDR=Yes';"
                
                Set oRS = CreateObject("ADODB.Recordset")
                    oRS.Open "SELECT DISTINCT " & Field & " FROM " & Table, oConn, 1, 1
                        Uniques = oRS.GetRows()
                    oRS.Close
                    
                    For Each Unique In Uniques
                        oRS.Open "SELECT COUNT(" & Field & ") FROM " & Table & " WHERE " & Field & "='" & Unique & "';", oConn, 1, 1
                            Worksheets("Desired Outcome").Range("B8:C8").Offset(n, 0).Value = Array(Unique, oRS.Fields(0).Value)
                        oRS.Close
                        n = n + 1
                    Next Unique
                    
            oConn.Close
            
    End Sub
    Attached Files Attached Files

  14. #14
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @Leith Ross, thank you very much for taking the time to come back to me with this.

    I've downloaded the file you've kindly provided and unfortuately there is no change to the previous one you posted.

    I have however tried your code in my live sheet and unfortuantely this doesn't quite provide the desired results. Rather than listing the unique entries from column D, the code lists the values from column B.

    Many thanks and kind regards

  15. #15
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: VBA Count Unique Values

    Hello hobbiton73,

    It is easy to change the source parameters. There are three: Worksheet, Starting Cell of the data, and the Column Header. the variable names are Wks, Rng, and Field respectively.

    To sort on column D instead of B, the Fieild needs to be changed to match column D header.

    If the data does not start at B7 then the variable Rng must be changed.

    If you don't feel you can make the needed changes or have problems doing so then post the workbook you will actually be using. I will make the changes for you.

  16. #16
    Forum Contributor
    Join Date
    08-17-2013
    Location
    India
    MS-Off Ver
    Excel 2007
    Posts
    132

    Re: VBA Count Unique Values

    Hi Nielm, I too applied your code with given spreadsheet and worked well.
    Would you mind applying comments to your code. Particularly for below two lines:
      .Item(x(i, 3)) = Array(j, "~" & x(i, 1) & "~")
                y(j, 1) = x(i, 3)
                y(j, 2) = 1
            Else
                t() = .Item(x(i, 3))
                If InStr(t(1), "~" & x(i, 1) & "~") = 0 Then
                    t(1) = t(1) & x(i, 1) & "~"
                    y(t(0), 2) = y(t(0), 2) + 1
                    .Item(x(i, 3)) = t()
    Thanks for your time.

    Regards,
    Last edited by Leith Ross; 04-01-2014 at 03:05 PM. Reason: Fixed Code Tags

  17. #17
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @BS Singh, thank you for taking the time to look at my post.

    If it helps, although I too am looking forward to see the code annotations by @nilem, please find the full working code below:

    Sub ertert()
    Dim x, y(), i&, j&, t()
    With Sheets("In Flight Projects")
        x = .Range("B8:D" & .Cells(Rows.Count, 2).End(xlUp).Row).Value
    End With
    With Sheets("Desired Outcome")
        .Range("B8:C" & .Cells(Rows.Count, 2).End(xlUp).Row + 1).ClearContents
    End With
    ReDim y(1 To UBound(x), 1 To 2)
    With CreateObject("Scripting.Dictionary")
        .CompareMode = 1
        For i = 1 To UBound(x)
            If Not .Exists(x(i, 3)) Then
                j = j + 1
                .Item(x(i, 3)) = Array(j, "~" & x(i, 1) & "~")
                y(j, 1) = x(i, 3)
                y(j, 2) = 1
            Else
                t() = .Item(x(i, 3))
                If InStr(t(1), "~" & x(i, 1) & "~") = 0 Then
                    t(1) = t(1) & x(i, 1) & "~"
                    y(t(0), 2) = y(t(0), 2) + 1
                    .Item(x(i, 3)) = t()
                End If
            End If
        Next i
        Sheets("Desired Outcome").Range("B8:C8").Resize(j) = y()
        Sheets("Desired Outcome").Activate
    End With
    End Sub
    Many thanks and kind regards

  18. #18
    Forum Contributor
    Join Date
    05-26-2012
    Location
    United Kingdom
    MS-Off Ver
    Excel 2013
    Posts
    682

    Re: VBA Count Unique Values

    Hi @Leith Ross, thank you for taking the time to come back to me with this and for the clear explanation.

    I fell comfortable in making the changes.

    If it help, I was also fortunate to receive an alternative working solution from @nilem which I've posted previously.

    Many thanks and kind regards

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

Similar Threads

  1. [SOLVED] Find count of Unique or Duplicate Values based on Concatenated values in 2 columns
    By bdicarlo1 in forum Excel Formulas & Functions
    Replies: 9
    Last Post: 12-03-2014, 12:42 AM
  2. [SOLVED] Macro to give the count of unique values after comparing the comma separated values
    By Manish_Gupta in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 03-03-2014, 12:41 AM
  3. [SOLVED] count unique values based on unique values
    By neetu.aggarwal in forum Excel General
    Replies: 13
    Last Post: 10-23-2012, 04:00 AM
  4. [SOLVED] How To Count Unique Values in COL A Subject for each unique value in COL B ??
    By amirtehrani in forum Excel Formulas & Functions
    Replies: 6
    Last Post: 06-06-2012, 03:00 AM
  5. Replies: 17
    Last Post: 08-24-2009, 08:58 AM

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