I have an excel sheet where there are 7 columns. I need to get unique count of users(in column A) based on filtering column C(Active - A, Inactive - I). Example
User_ID Status
A1 A
A2 I
A1 A
A3 I
A2 I
Currently, I am using below code to get total count of the column but I need to first filter Status=A, then get unique count of column User_ID if any duplicates are there in column A. I searched on the internet but was not able to find any proper solution, I am very new to VBA so kindly help.
DSheet.Range("A2").End(xlDown).Row
Use
Collection
Private Sub Test()
Dim Test As New Collection
Dim Test1 As New Collection
Dim rng As Range
For i = 2 To 6 'replace 6 with last row number
Value = Cells(i, "A").Value
check = Contains(Test, Value)
check1 = Contains(Test1, Value)
If Cells(i, "B").Value = "A" And Not check And Len(Value) > 0 Then
MsgBox Value
Test.Add Value, CStr(Value)
ElseIf Cells(i, "B").Value = "I" And Not check1 And Len(Value) > 0 Then
Test1.Add Value, CStr(Value)
End If
Next i
On Error GoTo 0
MsgBox Test.count ' Distinct count for Status A
MsgBox Test1.count ' Distinct count for Status I
End Sub
'Function to check if the value exists in collection.
Public Function Contains(col As Collection, key As Variant) As Boolean
Dim obj As Variant
On Error GoTo err
Contains = True
obj = col(key)
Exit Function
err:
Contains = False
End Function
Thank you so much for your help. I was able to execute through shorter code. I am filtering one column and getting unique counts based on filtered values. Sharing the code:
SSheet.Range("$A:$S").Autofilter field:=2, Criteria1:="A"
Set List=CreateObject(Scripting.Dictionary)
For Each ids In SSheet.Range("A2:A" & LastRow).SpecialCells(xlCellTypeVisible)
If Not List.Exists(ids.Value) Then List.Add ids.Value, Nothing
Next
MsgBox List.count
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.