VBA EXCEL将特定列的数组成员添加到集合以计算唯一值

时间:2017-12-12 11:20:01

标签: arrays excel vba count unique

我需要一个公共函数来获取数组并计算特定列中的值。 我写了以下内容,并重新订阅了超出范围的消息。

Public Function CountUarrcol(inarr() As Variant, colidx As Integer) As Long
 Dim col As New Collection
 Dim i As Integer
 Dim element As Variant

 For i = 0 To UBound(inarr, colidx)
    For Each element In inarr(i + 1, colidx)
        col.Add Item:=CStr(element.value), Key:=CStr(element.value)
    Next
 Next i
 CountUarrcol = col.Count   End Function

2 个答案:

答案 0 :(得分:0)

假设您想在数组的指定列中计算不同的值,这里有一个示例,其中从工作表范围读入5 * 3数组,计算第2列中的不同值。我使用的是函数Mark Nold检查要添加的值是否已存在于集合中。

Option Explicit

Public Sub test()

    Dim testArr()
    Dim myCount As Long

    testArr = ActiveSheet.Range("A1:C5").Value

    myCount = CountUarrcol(testArr, 2)

    MsgBox myCount

End Sub

Public Function CountUarrcol(inarr() As Variant, colidx As Long) As Long

    Dim col As New Collection
    Dim i As Long

    For i = 1 To UBound(inarr)

        If Not InCollection(col, CStr(inarr(i, colidx))) Then

            col.Add Item:=CStr(inarr(i, colidx)), key:=CStr(inarr(i, colidx))

        End If

    Next i

    CountUarrcol = col.Count

End Function

'Mark Nold  https://stackoverflow.com/questions/137845/determining-whether-an-object-is-a-member-of-a-collection-in-vba

Public Function InCollection(col As Collection, key As String) As Boolean
    Dim var As Variant
    Dim errNumber As Long

    InCollection = False
    Set var = Nothing

    Err.Clear
    On Error Resume Next
    var = col.Item(key)
    errNumber = CLng(Err.Number)
    On Error GoTo 0

    '5 is not in, 0 and 438 represent incollection
    If errNumber = 5 Then                        ' it is 5 if not in collection
        InCollection = False
    Else
        InCollection = True
    End If

End Function

Running macro

答案 1 :(得分:0)

没关系。我们需要2个子来做到这一点:

Public Function CountUvalinarrcol(ByRef inarr As Variant, ByVal colidx As Integer) As Long
     Dim col As New Collection
     Dim i As Integer
     Dim element As Variant

     For i = 1 To UBound(inarr)
     element = inarr(i, colidx)

         If colContains(col, element) = False Then
            col.Add item:=CStr(element)
         End If
     Next i
     CountUvalinarrcol = col.Count
End Function

另一个是:

    Public Function colContains(colin As Collection, itemin As Variant) As Boolean
Dim item As Variant
  colContains = False
  For Each item In colin
    If item = itemin Then
      colContains = True
      Exit Function
    End If
  Next
End Function

调用上述函数:

sub test()
dim x as long
x= CountUvalinarrcol(lsarr, 0)
end sub