[英]Get unique count of column values in VBA based on filtering another column
我有一個 excel 表,其中有 7 列。 我需要根據過濾列 C(活動 - A,非活動 - I)獲得唯一的用戶數(在 A 列中)。 例子
User_ID Status
A1 A
A2 I
A1 A
A3 I
A2 I
目前,我正在使用下面的代碼來獲取列的總數,但我需要先過濾 Status=A,然后獲取列 User_ID 的唯一計數,如果 A 列中有任何重復項。我在互聯網上搜索但無法找到任何合適的解決方案,我對 VBA 很陌生,所以請提供幫助。
DSheet.Range("A2").End(xlDown).Row
用
收藏
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
非常感謝你的幫助。 我能夠通過更短的代碼執行。 我正在過濾一列並根據過濾后的值獲取唯一計數。 分享代碼:
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.