简体   繁体   中英

Count unique entries between blanks Excel

I would like to count unique entries in a range between blanks. Please look at the attached pic for reference. The first set of data contains 3 unique entries so the highlighted box would 3. The second set of data has 3 unique entries and the highlighted box then would also display 3.

example

Assuming you want to do this in VBA and the range containing the data sets is huge, the question is not as trivial as others which have replied to this post have made it out to be.

The following code requires that you set a reference to the Microsoft Scripting Runtime library. It inserts the number of unique values each time it finds an empty row in the search range (works best if there is only one empty row to separate the different data sets in the range):

Option Explicit

Sub uniquesEntriesInDataSets()

    Dim dict As Scripting.Dictionary
    Dim i As Long, startAt As Long, uCount As Long
    Dim cll As Range, searchRange As Range
    Dim val As Variant

    ' change sheetname and range to relevant parameters
    Set searchRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A21")

    Set dict = New Dictionary

    For Each cll In searchRange

        val = cll.Value

        If val = vbNullString Then
            If dict.Count > 0 Then 
                cll.Value = dict.Count
                dict.RemoveAll
            End if
        Else
            If Not dict.Exists(val) Then dict.Add Key:=val, Item:=i
        End If

    Next cll

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM