vba统计一列里每个数据出现的次数
时间: 2023-12-19 19:06:56 浏览: 60
可以使用 VBA 中的 Dictionary 对象来统计一列中每个数据出现的次数。以下是一个示例代码:
```vb
Sub CountOccurrences()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Dim i As Long
For i = 1 To lastRow
Dim currentValue As String
currentValue = Cells(i, 1).Value
If Not myDict.Exists(currentValue) Then
myDict.Add currentValue, 1
Else
myDict(currentValue) = myDict(currentValue) + 1
End If
Next i
'输出结果
Dim key As Variant
For Each key In myDict.Keys
Debug.Print key & ": " & myDict(key)
Next key
End Sub
```
这个代码会遍历第一列中的所有单元格,把每个值添加到 Dictionary 对象中。如果这个值已经存在于 Dictionary 中,那么对应的计数器就加 1。最后输出每个值和它出现的次数。