简体   繁体   English

Excel VBA-公式计数唯一值错误

[英]Excel VBA - Formula Counting Unique Value error

I am trying to calculate the count of Unique values based on a condition. 我正在尝试根据条件计算唯一值的计数。

For example, 例如,

For a value in column B, I am trying to count the Unique values in Column C through VBA. 对于B列中的值,我试图通过VBA计算C列中的“唯一”值。

I know how to do it using Excel formula - 我知道如何使用Excel公式-

 =SUMPRODUCT((B2:B12<>"")*(A2:A12=32)/COUNTIF(B2:B12,B2:B12))

that value for 32 is dynamic - Programmatically I am calling them inside my vba code as Name 32的值是动态的-以编程方式我在vba代码中将它们称为Name

This is my code : 这是我的代码:

Application.WorksheetFunction.SumProduct((rng <> "") * (rng2 = Name) / CountIfs(rng, rng))

This is the sample data with the requirement 这是带有要求的样本数据

数据

Alternatively, I Concatenated both the columns for keeping it simple and hoping to identify the Unique values which starts with name* method. 另外,我将这两列连接起来以保持简单,并希望标识以name *方法开头的Unique值。

I don't know where I am going wrong. 我不知道我要去哪里错了。 Kindly share your thoughts. 请分享您的想法。

You may try something like this... 您可以尝试这样的事情...

Function GetUniqueCount(Rng1 As Range, Lookup As String) As Long
Dim x, dict
Dim i As Long, cnt As Long
Set dict = CreateObject("Scripting.Dictionary")
x = Rng1.Value
For i = 1 To UBound(x, 1)
    If x(i, 1) = Lookup Then
        dict.Item(x(i, 1) & x(i, 2)) = ""
    End If
Next i
GetUniqueCount = dict.Count
End Function

Then you can use it like below... 然后您可以像下面一样使用它...

=GetUniqueCount($A$2:$B$10,C2)

Where A2:B10 is the data range and C2 is the name criteria. 其中A2:B10是数据范围,而C2是名称标准。

在此处输入图片说明

在此处输入图片说明

I'd put the values into an array, create a temporary 2nd array and only add values to this array if they are not already present, and then replace the original array. 我将这些值放入一个数组中,创建一个临时的第二个数组,仅在尚不存在的情况下将值添加到该数组中,然后替换原始数组。 Then it's just a simple matter to sum the unique values: 然后,将唯一值相加就很简单了:

Sub Unique

dim arr(10) as variant, x as variant
dim arr2() as variant

for x = 1 to 10 ' or whatever
   arr(x) = cells(x, 1) ' or whatever
next x

arr2 = UniqueValuesArray(arr)

' now write some code to count the unique values, you get the idea

End Sub

Function UniqueValuesArray(arr As Variant) As Variant()

Dim currentRow, arrpos As Long
Dim uniqueArray() As Variant
Dim x As Long

arrpos = 0
ReDim uniqueArray(arrpos)

For x = 0 To UBound(arr)
    If UBound(Filter(uniqueArray, arr(x))) = -1 Then
        ReDim Preserve uniqueArray(arrpos)
        uniqueArray(arrpos) = arr(x)
        arrpos = arrpos + 1
    End If
Next x

UniqueValuesArray = uniqueArray

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM