[英]Counting number of unique days that a certain value falls in using Excel FOrmula
[英]Excel VBA - Formula Counting Unique Value error
我正在嘗試根據條件計算唯一值的計數。
例如,
對於B列中的值,我試圖通過VBA計算C列中的“唯一”值。
我知道如何使用Excel公式-
=SUMPRODUCT((B2:B12<>"")*(A2:A12=32)/COUNTIF(B2:B12,B2:B12))
32的值是動態的-以編程方式我在vba代碼中將它們稱為Name
這是我的代碼:
Application.WorksheetFunction.SumProduct((rng <> "") * (rng2 = Name) / CountIfs(rng, rng))
這是帶有要求的樣本數據
另外,我將這兩列連接起來以保持簡單,並希望標識以name *方法開頭的Unique值。
我不知道我要去哪里錯了。 請分享您的想法。
您可以嘗試這樣的事情...
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
然后您可以像下面一樣使用它...
=GetUniqueCount($A$2:$B$10,C2)
其中A2:B10是數據范圍,而C2是名稱標准。
我將這些值放入一個數組中,創建一個臨時的第二個數組,僅在尚不存在的情況下將值添加到該數組中,然后替換原始數組。 然后,將唯一值相加就很簡單了:
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.