创建一个包含值和键的列表,并获取最大值

时间:2016-06-14 08:29:56

标签: vba excel-vba excel

我有以下虚拟数据

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类)。关于如何提取这个值的任何想法?

2 个答案:

答案 0 :(得分: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

此代码也将打印

  

最高!

答案 1 :(得分: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