想请教各位版大,以下有一function,其作用是将item_range中的项目对number_range
进行累加并回传第rank_order大之项目名称,但有时会有两个项目的累加金额相同,这
时候如果使用match函数则只会取首位,因此会出现第1名和第2名皆为同一项目名称的问
题。
在下面程式中我if…then的方式进行判断,虽然可以解决这个问题,不过程式看起来有点
冗长,不知道有没有更为简短的写法? 谢谢!
Function inventory_rank4(item_range As Range, number_range As Range, _
rank_order As Integer) As String
Dim r As Range
Dim ary(10)
Dim w&, dic
Set dic = CreateObject("scripting.dictionary")
For Each r In item_range
If r <> "" Then If Not dic.exists(r.Value) Then _
dic.Add r.Value, r.Value: _
ary(w) = WorksheetFunction.SumIf(item_range, r, number_range): _
w = w + 1
Next
If rank_order = 1 Then
inventory_rank4 = dic.Items()(WorksheetFunction.Match( _
WorksheetFunction.Large(ary, rank_order), ary, 0) - 1)
Else
If WorksheetFunction.Large(ary, rank_order) = _
WorksheetFunction.Large(ary, rank_order - 1) Then
ary(WorksheetFunction.Match(WorksheetFunction.Large(ary, _
rank_order), ary, 0) - 1) = 0
inventory_rank4 = dic.Items()(WorksheetFunction.Match( _
WorksheetFunction.Large(ary, rank_order - 1), ary, 0) - 1)
Else
inventory_rank4 = dic.Items()(WorksheetFunction.Match( _
WorksheetFunction.Large(ary, rank_order), ary, 0) - 1)
End If
End If
End Function