Excel VBA:輸入key和value兩個單元格區域,以value的值比較排序,然後返回key的排序
阿新 • • 發佈:2021-02-10
程式碼部分:
Option Explicit Sub example() Dim key As Range Dim value As Range Dim updown As Integer, rankNum As Integer Set key = Sheet1.Range("A2:A8") Set value = Sheet1.Range("B2:B8") updown = 0 rankNum = 3 MsgBox sortRange(key, value, updown, rankNum) End Sub Function sortRange(key As Range, value As Range, updown As Integer, rankNum As Integer) '函式功能:輸入key和value兩個單元格區域,以value的值比較排序,然後返回key的排序。 '程式碼邏輯:用rank()公式函式把value區域的值排名、存值,然後取出排名靠前的多少個key值。 'key:排序後顯示的名稱區域 'value:用於排序比較的數值區域 'updown:0為降序排,非0為升序排 'rankNum:只要求排名的前多少位 Dim longArr As Integer Dim i, j As Integer Dim out As String If key.Columns.Count = 1 And value.Columns.Count = 1 Then If key.Rows.Count = value.Rows.Count Then longArr = key.Rows.Count ReDim order(1 To longArr) As Integer For i = 1 To longArr '排名、存值 order(i) = Application.WorksheetFunction.Rank(value(i), value, updown) '任何時候不能用省略寫法,坑。 Next i For j = 1 To rankNum '取出排名靠前的key值 For i = 1 To longArr If order(i) = j Then If out = "" Then out = key(i) Else out = out & "、" & key(i) End If End If Next i Next j sortRange = out Else MsgBox "錯誤:兩區域長度不等。" End End If Else MsgBox "錯誤:其中一區域包含兩列及以上。" End End If End Function
Excel的示例資料:
結果: