2016-06-14 83 views
0

我有以下的僞數據創建值和密鑰列表,並獲得最大值

Dim count1 As Integer 
Dim count2 As Integer 
Dim count3 As Integer 
Dim count4 As Integer 
Dim count5 As Integer 

count1 = 0 
count2 = 3 
count3 = 2 
count4 = 0 
count5 = 1 

使用下面的代碼我的值添加到字典

Dim key As Variant 
Dim dic As Object 
Set dic = CreateObject("Scripting.Dictionary") 

    dic.Add "Category 1", count1 
    dic.Add "Category 2", count2 
    dic.Add "Category 3", count3 
    dic.Add "Category 4", count4 
    dic.Add "Category 5", count5 

我想但現在要做的是獲得屬於最高計數的類別(在本例中爲 類別2)。有關如何提取此值的任何想法?

+0

歡迎SO。請閱讀[如何問](http://stackoverflow.com/help/how-to-ask)。簡而言之,您需要顯示您的代碼嘗試解決此問題,以及它無法獲得最多幫助的位置在這個網站上。如果您還張貼了您的工作表樣本的屏幕截圖,那也可以幫助我們更好地幫助您。 – Moosli

+0

@Moosli,好的,請記住。更新我的問題 –

回答

1

您需要先添加密鑰,然後添加項目。

見示例代碼(請注意,我用的字典早期綁定,它讓生活變得更輕鬆):

Sub DictionaryKeyTest() 
    Dim d As Scripting.Dictionary 
    Set d = New Dictionary 
    d.Add 2, "notHighest" 
    d.Add 3, "alsoNotHighest" 
    d.Add 10, "Highest!" 
    d.Add 4, "alsoAlsoNotHighest" 

    Debug.Print d(Application.Max(d.Keys)) 
End Sub 

如果你運行這段代碼,立即窗口將顯示:

最高!

如果你需要跑來跑去此相反,說,如果幾個類別可以有相同的計數值(或其他一些場景類別是關鍵),有沒有辦法做什麼你想不循環所有的值來找到最大的值。例如:

Sub DictionaryHighestItemCounter() 
    Dim d As Scripting.Dictionary 
    Set d = New Dictionary 
    d.Add "notHighest", 2 
    d.Add "alsoNotHighest", 2 
    d.Add "Highest!", 10 
    d.Add "alsoAlsoNotHighest", 4 

    Dim highestVal As Long, s As String 
    For Each i In d.Keys 
     If d(i) > highestVal Then 
      highestVal = d(i) 
      s = i 
     End If 
    Next i 

    Debug.Print s 
End Sub 

此代碼也將打印

最高!

0

,你可以使用數組:

Option Explicit 

Sub GetCategory()  
    Dim catsArray As Variant, valsArray As Variant 

    catsArray = Array("Category 1", "Category 2", "Category 3", "Category 4", "Category 5") 
    valsArray = Array(0, 3, 2, 0, 1) 

    MsgBox "The winner is: " & catsArray(WorksheetFunction.Match(WorksheetFunction.Max(valsArray), valsArray, 0) - 1) 
End Sub 

,將工作,你應該一定要用變量的值,以及:

Option Explicit 

Sub GetCategory2() 
    Dim catsArray As Variant, valsArray As Variant 
    Dim count1 As Integer: count1 = 0 
    Dim count2 As Integer: count2 = 3 
    Dim count3 As Integer: count3 = 2 
    Dim count4 As Integer: count4 = 0 
    Dim count5 As Integer: count5 = 1 

    catsArray = Array("Category 1", "Category 2", "Category 3", "Category 4", "Category 5") 
    valsArray = Array(count1, count2, count3, count4, count5) 

    MsgBox "The winner is: " & catsArray(WorksheetFunction.Match(WorksheetFunction.Max(valsArray), valsArray, 0) - 1) 
End Sub