[英]Get unique count of column values in VBA based on filtering another column
I have an excel sheet where there are 7 columns.我有一个 excel 表,其中有 7 列。 I need to get unique count of users(in column A) based on filtering column C(Active - A, Inactive - I).
我需要根据过滤列 C(活动 - A,非活动 - I)获得唯一的用户数(在 A 列中)。 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.目前,我正在使用下面的代码来获取列的总数,但我需要先过滤 Status=A,然后获取列 User_ID 的唯一计数,如果 A 列中有任何重复项。我在互联网上搜索但无法找到任何合适的解决方案,我对 VBA 很陌生,所以请提供帮助。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.