vba先分类汇总,然后按条件查找销量top10
时间: 2023-06-02 11:02:46 浏览: 71
Sub SalesTop10()
Dim ws As Worksheet
Dim lastRow As Long
Dim rng As Range
Dim dict As Object
Dim key As Variant
Dim i As Long
Dim j As Long
Dim arr() As Variant
'设置工作表和最后一行
Set ws = ThisWorkbook.Worksheets("Sheet1")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'设置范围并将数据存储到字典中
Set rng = ws.Range("A2:C" & lastRow)
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To rng.Rows.Count
If Not dict.exists(rng.Cells(i, 1).Value) Then
dict.Add rng.Cells(i, 1).Value, Array(0, 0)
End If
dict(rng.Cells(i, 1).Value)(0) = dict(rng.Cells(i, 1).Value)(0) + rng.Cells(i, 3).Value
Next i
'将字典中的数据存储到数组中
ReDim arr(1 To dict.Count, 1 To 2)
i = 1
For Each key In dict
arr(i, 1) = key
arr(i, 2) = dict(key)(0)
i = i + 1
Next key
'按销量排序
For i = 1 To UBound(arr) - 1
For j = i + 1 To UBound(arr)
If arr(i, 2) < arr(j, 2) Then
Dim temp As Variant
temp = arr(i, 1)
arr(i, 1) = arr(j, 1)
arr(j, 1) = temp
temp = arr(i, 2)
arr(i, 2) = arr(j, 2)
arr(j, 2) = temp
End If
Next j
Next i
'输出前十个
For i = 1 To 10
If i <= UBound(arr) Then
Debug.Print arr(i, 1) & " - " & arr(i, 2)
End If
Next i
End Sub