【问题标题】:Get unique count of column values in VBA based on filtering another column基于过滤另一列获取VBA中列值的唯一计数
【发布时间】:2020-03-04 07:58:07
【问题描述】:

我有一个 7 列的 Excel 表。我需要根据过滤列 C(Active - A,Inactive - I)获取唯一的用户计数(在 A 列中)。示例

User_ID  Status
A1        A
A2        I
A1        A
A3        I
A2        I

目前,我正在使用下面的代码来获取列的总数,但我需要先过滤 Status=A,然后如果 A 列中有任何重复项,则获取列 User_ID 的唯一计数。我在互联网上搜索但找不到任何合适的解决方案,我对 VBA 很陌生,所以请帮忙。

DSheet.Range("A2").End(xlDown).Row

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    使用

    收藏

    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
    

    【讨论】:

    • 能否请您简要解释一下用 For 循环编写的代码。
    • 我用过两个系列。一种用于Status=A,另一种用于Status=I。然后,我根据使用Contains Function 不应该存在于相应集合中的条件在两个集合中插入值。这样,两个集合中的项目都是唯一的。
    【解决方案2】:

    非常感谢您的帮助。我能够通过更短的代码执行。我正在过滤一列并根据过滤值获取唯一计数。分享代码:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      相关资源
      最近更新 更多