无法根据VBA中的两个条件计算计数?
我试图通过在Excel中使用VBA来基于两个条件来计算一些数据occerence的计数。 下面是我试图实现的场景:
有一个Excel表格说SHEET1具有如下所述的数据。
|Contract No| Ledger No| | Con1 | Led1 | | Con1 | Led2 | | Con1 | Led3 | | Con2 | Led4 | | Con2 | Led2 | | Con3 | Led5 | | Con3 | Led6 | | Con3 | Led3 |
还有另一个Excel工作表说SHEET2有基础数据对应于分类帐号 。
| Ledger No| ProductBaught | Led1 | P1 | Led1 | P2 | Led1 | P3 | Led2 | P4 | Led2 | P3 | Led3 | P2 | Led3 | P1 | Led3 | P4 | Led4 | P2 | Led4 | P3 | Led5 | P1 | Led6 | P4
我在找下面的计算(根据合同号计算产品数量)。这里Cont1 = Led1(P1,P2,P3),Led2(P4,P3),Led3(P2,P1,P4),所以计数是P1,P2 ,P3,P4的意思是4.同样适用于其他的数字。
|Contract No| Count of Products Baught| | Con1 | 4 | | Con2 | 3 | | Con3 | 3 |
我正在这样想。
将字段中的合同号和分类帐号存储为键值对。 以一个Key的多个值的forms。 所以字典将只有三个关键字Con1,Con2,Con3和Ledger数字将是相应的值。
Integer count Foreach Key in Dictionary.Keys() count = 0 Foreach Value in Key.Values() IF(Lookup in SHEET2 = True) count = count + 1 END IF Next Value First column in Result Sheet = Key Second column in Result Sheet = count Next Key
我仍然无法找出正确的方法,因为这个计数也不是所需的数量,因为它将P1,P2,P1的计数视为3而不是2。我必须在VBA中实现这一点,而我不知道我的想法是否正确。
感谢帮助。
谢谢,亲爱的
你可以使用这个UDF:
Function COUNTX(crit As String, critrng As Range, prdrng As Range) As Long Dim critArr, prdArr Dim i&, j& Set dict = CreateObject("Scripting.Dictionary") critArr = critrng.Value prdArr = prdrng.Value For i = LBound(critArr, 1) To UBound(critArr, 1) If critArr(i, 1) = crit Then For j = LBound(prdArr, 1) To UBound(prdArr, 1) If prdArr(j, 1) = critArr(i, 2) Then On Error Resume Next dict.Add prdArr(j, 2), prdArr(j, 2) On Error GoTo 0 End If Next j End If Next i COUNTX = dict.Count End Function
把它放在一个附加到工作簿的模块中,而不是在工作表代码或ThisWorkbook代码中。
那么你可以这样称呼它像一个正常的公式:
=COUNTX(A1,Sheet1!$A$2:$B$9,Sheet2!$A$2:$B$13)
三个标准是:
- 合同号码的string。
- 第一张,两列的范围。 在这个范围内,UDF将search合同的第一列,并使用第二列作为分类帐。
- 第二张,两列的范围。 它将search第一列,并使用第二列产品。