参考下面的excel屏幕截图,我正在寻找一个公式解决方案,该解决方案针对A列中的每个ID编号计算B列(颜色)中唯一值的数量。
我在C列中估算了期望的结果。因此,例如,ID 1(A2)仅具有一种唯一的颜色,灰色(B2),它将在C2中返回1。ID 2仅具有一种唯一的颜色黄色(B3,B4),并在C3和C4中返回1。ID 3具有两种独特的颜色,蓝色和紫色,因此在C5至C8中返回2。等等。
因为这将运行近100,000行,所以我遇到的许多基于索引和/或匹配的解决方案都需要很长时间才能进行计算。我发现ID值都是按升序排列的,它们可以通过以= IF(A2 = A1或类似的东西)开头的公式来加快处理速度,这要感谢任何对如何使用用一个瘦的公式解决这个问题。
注意:我正在处理也有接近100列的文件。不需要辅助列的解决方案将是理想的。
编辑/添加:在我的主数据文件中,B列中有空白单元格的实例。计数C列结果时是否可以忽略空白单元格?
这是一个VBA例程,应针对该数目的条目快速运行。我们创建一个类模块(用户定义的对象),该模块由与每个ID相关联的颜色的集合(字典)和该颜色的计数组成。(实际上并不需要计数,但是如果您出于其他目的想要添加计数,这是微不足道的;也可以作为一些可以完成的演示)。
然后,如您在屏幕截图中所示,我们将结果输出到相邻的列中。只需稍作更改,结果就可以输出到其他地方,甚至可以输出到其他工作表上。
请务必阅读模块开头的说明,以获取重要信息以及正确进行设置。
Option Explicit
'RENAME this module: cID
Private pID As String
Private pColor As String
Private pColors As Dictionary
Public Property Get ID() As String
ID = pID
End Property
Public Property Let ID(Value As String)
pID = Value
End Property
Public Property Get Color() As String
Color = pColor
End Property
Public Property Let Color(Value As String)
pColor = Value
End Property
Public Property Get Colors() As Dictionary
Set Colors = pColors
End Property
Public Function ADDColor(Value As String)
'Might as well also count # of times this color assigned
If Not pColors.Exists(Value) Then
pColors.Add Key:=Value, Item:=1
Else
pColors(Value) = pColors(Value) + 1
End If
End Function
Private Sub Class_Initialize()
Set pColors = New Dictionary
End Sub
编辑(进行编辑以消除空白行的计数)
Option Explicit
'Set reference to Microsoft Scripting Runtime (Tools/References)
Sub IDColorCount()
Dim cID As cID, dID As Dictionary
Dim wsData As Worksheet, rData As Range
Dim vData As Variant, vRes As Variant
Dim I As Long
'Set the data worksheet and range
'Read the data into an array for faster calculations
Set wsData = Worksheets("sheet1")
With wsData
Set rData = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(columnsize:=2)
vData = rData
End With
'Go through the data and collect the information
Set dID = New Dictionary
For I = 2 To UBound(vData, 1)
If Not vData(I, 1) = "" Then
Set cID = New cID
With cID
.ID = vData(I, 1)
.Color = vData(I, 2)
.ADDColor .Color
If Not dID.Exists(.ID) Then
dID.Add Key:=.ID, Item:=cID
Else
dID(.ID).ADDColor .Color
End If
End With
End If
Next I
'Size the results array
ReDim vRes(1 To UBound(vData), 1 To 1)
vRes(1, 1) = "Count"
For I = 2 To UBound(vData, 1)
If Not vData(I, 1) = "" Then _
vRes(I, 1) = dID(CStr(vData(I, 1))).Colors.Count
Next I
'The results can be written anyplace
With rData.Offset(0, 2).Resize(columnsize:=1)
.EntireColumn.Clear
.Value = vRes
End With
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句