VBA宏和Excel高级筛选结果对计数唯一元素不匹配

时间:2013-11-21 21:52:29

标签: excel vba excel-vba

我的问题是我必须写一个宏,它从列中返回唯一元素。我现在可以使用高级过滤器,但我必须使用宏来进行分配。我可以使用过滤器测试宏的结果,有时宏会给出好的结果,有时则不会。我知道选择,选择部分要求我留在列的第一行。代码是:

Sub ElemSzámolás()
    Dim lista() As String
    Dim k As Integer
    Dim oszlop As Range

    k = 1
    ReDim lista(0 to 1)

    Set oszlop = ActiveSheet.Range(Selection, Selection)

    Do While oszlop.Offset(k).Value <> ""
        If UBound(Filter(lista, oszlop.Offset(k).Value)) = -1 Then
            lista(Ubound(lista)) = oszlop.Offset(k).Value
            ReDim Preserve lista(0 to UBound(lista) + 1)
        End If
        k = k + 1
    Loop

    MsgBox UBound(lista) & " db műsor van a listában", vbOKOnly, "Eredmény"    
End Sub

提前致谢!

1 个答案:

答案 0 :(得分:0)

  

我的问题是我必须写一个宏,它从列中返回唯一元素。

这是你在尝试什么?这也适用于多列。

Sub ElemSzámolás()
    Dim oszlop As Range, aCell As Range
    Dim col As New Collection, itm

    '~~> Check if what the user selected is a valid range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Select a range first."
        Exit Sub
    End If

    Set oszlop = Selection

    '~~> Create a unique collection
    For Each aCell In oszlop
        If Not aCell = "" Then
            On Error Resume Next
            col.Add aCell.Value, CStr(aCell.Value)
            On Error GoTo 0
        End If
    Next

    '~~> This will give you the unique count
    MsgBox col.count & " unique items found"

    '~~> This will give you each of those unique items
    For Each itm In col
        Debug.Print itm
    Next
End Sub

enter image description here