用 vba 写一段代码,在一个数据出现时,这个数据下面一行的其他数据出现的次数,并排序
时间: 2024-02-29 13:51:31 浏览: 112
好的,以下是一个简单的 VBA 代码,它可以实现您的要求:
```vba
Sub CountAndSort()
Dim lastRow As Long
Dim counter As Object
Dim i As Long
'获取最后一行
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
'创建计数器
Set counter = CreateObject("Scripting.Dictionary")
'循环遍历每一行
For i = 2 To lastRow
'获取当前行的值
Dim value As String
value = Cells(i, "A").Value
'如果当前值不为空
If value <> "" Then
'如果计数器已经包含了当前值
If counter.Exists(value) Then
'将对应的计数器加一
counter(value) = counter(value) + 1
Else
'否则,将当前值添加到计数器中,并将计数器初始化为 1
counter.Add value, 1
End If
End If
Next i
'将结果按照出现次数从大到小排序
Dim keys() As Variant
keys = counter.keys
Dim values() As Variant
ReDim values(UBound(keys))
For i = 0 To UBound(keys)
values(i) = counter(keys(i))
Next i
Call QuickSort(values, keys, 0, UBound(keys))
'输出结果
For i = UBound(keys) To 0 Step -1
Debug.Print keys(i), values(i)
Next i
End Sub
Sub QuickSort(ByRef values As Variant, ByRef keys As Variant, ByVal left As Long, ByVal right As Long)
Dim pivot As Variant
Dim i As Long
Dim j As Long
pivot = values((left + right) \ 2)
i = left
j = right
Do While i <= j
Do While values(i) > pivot
i = i + 1
Loop
Do While values(j) < pivot
j = j - 1
Loop
If i <= j Then
Swap values, i, j
Swap keys, i, j
i = i + 1
j = j - 1
End If
Loop
If left < j Then
Call QuickSort(values, keys, left, j)
End If
If i < right Then
Call QuickSort(values, keys, i, right)
End If
End Sub
Sub Swap(ByRef arr As Variant, ByVal i As Long, ByVal j As Long)
Dim temp As Variant
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
End Sub
```
这段代码会遍历 A 列中的每一行数据,统计每个数据在 A 列中出现的次数,并且将出现次数从大到小排序输出。请将这段代码复制到 VBA 编辑器中,然后在 Excel 中按下 Alt + F8 打开宏对话框,选择 CountAndSort 并执行即可。
阅读全文