听到的想法是,一列包含80,000行,这些行填充了值,我想创建一个VBA宏,该宏将读取每个值并计算该列中存在多少次并打印它,但是问题是,当循环再次达到相同的数字,我不想再次打印,因为它已经被打印。
这是我到目前为止写的,但是我无法使它工作。
Option Explicit
Sub timesofattack()
Dim count As Long
Dim count2 As Long
Dim d As Long
Dim f As Long
Dim a As Long
Do Until IsEmpty(Cells(d, 2).Value)
f = d
Do Until IsEmpty(Cells(f, 2).Value)
If Cells(d, 2).Value = Cells(f, 2).Value Then
count = count + 1
End If
f = f + 1
Loop
If count = 1 Then
f = 8
Do Until IsEmpty(Cells(f, 2).Value)
If Cells(d, 2).Value = Cells(f, 2).Value Then
count2 = count2 + 1
End If
f = f + 1
Loop
Range("H8").Offset(a, 0).Value = Cells(d, 2).Value
Range("G8").Offset(a, 0).Value = count2
a = a + 1
End If
d = d + 1
Loop
End Sub
答案 0 :(得分:2)
Scripting.Dictionary
非常适合检索唯一值和计算重复项。
Sub timesofattack2()
Dim data As Variant, key As Variant, dic As Object
Set dic = CreateObject("Scripting.Dictionary")
With ThisWorkbook.Worksheets("Data")
data = .Range("B2", .Range("B" & .Rows.count).End(xlUp)).Value
End With
For Each key In data
dic(key) = dic(key) + 1
Next
With ThisWorkbook.Worksheets.Add
.Range("A2").Resize(dic.count).Value = Application.Transpose(dic.Keys())
.Range("B2").Resize(dic.count).Value = Application.Transpose(dic.Items())
End With
End Sub
答案 1 :(得分:0)
另一个在列表中每个项目的第一个出现的旁边写入计数的选项:
Sub timesofattack3()
Set P1 = Range("B1", Range("B999999").End(xlUp))
T1 = P1
Set D1 = CreateObject("scripting.dictionary")
Set D2 = CreateObject("scripting.dictionary")
For i = 1 To UBound(T1)
If Not D1.exists(T1(i, 1)) Then
D1.Add T1(i, 1), 1
D2.Add T1(i, 1), i
Else
D1(T1(i, 1)) = D1(T1(i, 1)) + 1
End If
Next i
For Each k In D2.keys
Cells(D2(k), 3) = D1(k)
Next
End Sub