我有一张Excel工作表,上面有按日期排序的日期和电子邮件地址列。我想计算在当前事件发生之前,电子邮件地址在工作表中的次数。COUNTIF(B$1:B1,B2)公式有效,但当我将其复制到50000多条记录时,Excel崩溃。我总共有20万张唱片。
Excel(2010)是否可以处理其他解决方案?
这里有一个在合理时间内运行的VBA子
Sub countPrior()
Dim dic As Object
Dim i As Long
Dim dat As Variant
Dim dat2 As Variant
' Get source data range, copy to variant array
dat = Cells(1, 2).Resize(Cells(Rows.Count, 1).End(xlUp).Row, 1)
' create array to hold results
ReDim dat2(1 To UBound(dat, 1), 1 To 1)
' use Dictionary to hold count values
Set dic = CreateObject("scripting.dictionary")
' loop variant array
For i = 1 To UBound(dat, 1)
If dic.Exists(dat(i, 1)) Then
' return count
dat2(i, 1) = dic.Item(dat(i, 1))
' if value already in array, increment count
dic.Item(dat(i, 1)) = dic.Item(dat(i, 1)) + 1
Else
' return count
dat2(i, 1) = 0
' if value not already in array, initialise count
dic.Add dat(i, 1), 1
End If
Next
' write result to sheet
Cells(1, 3).Resize(Cells(Rows.Count, 1).End(xlUp).Row, 1) = dat2
End Sub
如果宏是您的一个选项,这里有一个宏可以为您完成这一任务。我假设您的地址在B列,并且您希望在C列中记录之前出现的次数,您可以根据您的工作表的结构进行修改。
Sub countPrior()
Application.ScreenUpdating=False
bottomRow = Range("B1000000").End(xlUp).Row
For i = 2 To bottomRow
cellVal = Range("B" & i).Value
counter = 0
For j = 1 To i - 1
If Range("B" & j).Value = cellVal Then
counter = counter + 1
End If
Next j
Range("C" & i).Value = counter
Next i
Application.ScreenUpdating=True
End Sub