首頁 > 運動
excel宏實現自動排名vba程式碼
由 商業世界新訊 發表于 運動2021-06-18
簡介Sort Key1:=Range(“K1”), Order1:=xlDescending, Header:= _xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToB
excel怎麼自動排名次
實現功能:
銷售資料在全域性排名、在相同子類(可以是區域、分類)再對銷售進行各自排名
k列(11)為銷售資料,A列為子類,全域性排名資料存放到第15列,子類排名存放到第14列
可以對A、K列設為變數再賦值,提高程式碼移植的便利性
Sub SalesSeqence()
‘
’seqence Macro
‘宏由 mike 錄製
’
Dim RowN As Integer
Dim i As Integer
Dim colqA as integer,colqK as integer ‘2個參照資料列數
Dim colA as integer ’全域性排名填充列
Dim colB as integer ‘子類排名填充列
colqA=1
colqK=11
colA=15
colB=14
’獲取資料行數,減少後面的迴圈次數
For i = 1 To 20000
If Cells(i, colqK)。Value <>>
RowN = i
End If
Next i
‘子類不全時填充全——資料特殊格式可以略過
For i = 3 To RowN
If Cells(i, colqK)。Value <>>
Cells(i,colqA) = Cells(i - 1, colqA)
End If
Next i
’——————————-進行全域性排名
Columns(“K:K”)。Select
Range(“A1:O” & RowN)。Sort Key1:=Range(“K1”), Order1:=xlDescending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
SortMethod:=xlPinYin, DataOption1:=xlSortNormal
‘第一遍遍歷
Cells(2, colA)。Value = 1
For i = 3 To RowN
If Cells(i, colqK)。Value <>>
Cells(i, colA)。Value = Cells(i - 1, colA)。Value + 1
End If
Next i
’第二遍合併相同名次
For i = 3 To RowN
If Cells(i, colqK)。Value <>>
Cells(i, colA)。Value = Cells(i - 1, colA)。Value
End If
Next i
‘————————在子類進行排名
Columns(“k:k”)。Select
Range(“A1:O” & RowN)。Sort Key1:=Range(“k1”), Order1:=xlDescending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
SortMethod:=xlPinYin, DataOption1:=xlSortNormal
Columns(“A:A”)。Select
Range(“A1:O” & RowN)。Sort Key1:=Range(“A1”), Order1:=xlDescending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
SortMethod:=xlPinYin, DataOption1:=xlSortNormal
Cells(2, colB)。Value = 1
For i = 3 To RowN
If Cells(i, colqK)。Value <>>
Cells(i, colB)。Value = Cells(i - 1, colB)。Value + 1
ElseIf Cells(i, colqK)。Value <>> Cells(i - 1, colqA)。Value Then
Cells(i, colB)。Value = 1
End If
Next i
For i = 3 To RowN
If Cells(i, colqK)。Value <>>
Cells(i, colB)。Value = Cells(i - 1, colB)。Value
End If
Next i
End Sub