我正在使用VBA将键和与该键关联的值存储到字典中。
Sub Dict_Example()
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 to 5
dict.Add i, some number
Next i
我想在dict
中找到最大值及其关联的键。
例如,如果dict = {1:5,2:2,10,3:6,4:11,5:3}其中1,2,3,4,5是键,而5,10,6,11 ,3是值,则应返回4:11。
如何在VBA中执行此操作?
答案 0 :(得分:5)
我将从dict.items
生成一个数组,并在其上使用Max / Min函数。然后循环按键并与此进行比较。
Option Explicit
Public Sub Dict_Example()
Dim dict As Object, max As Long, min As Long, arr(), key As Variant, i As Long
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To 5
dict.Add i, i * Application.WorksheetFunction.RandBetween(0, 100)
Next i
max = Application.max(dict.items)
min = Application.min(dict.items)
For Each key In dict
Debug.Print key, dict(key)
If dict(key) = max Then Debug.Print "max= " & dict(key) & vbTab & "key= " & key
Next
Stop
End Sub
答案 1 :(得分:0)
您可以通过使用几个数组来临时存储您在字典中迭代时的高值和低值以及关联的键来实现此目的,
Sub test()
Dim dict As New Dictionary
Dim low(1 To 2)
Dim high(1 To 2)
Dim i As Long
Dim key
For i = 1 To 5
dict.Add i, 'some number
Next i
low(1) = dict.Keys(0)
low(2) = dict(dict.Keys(0))
high(1) = dict.Keys(0)
high(2) = dict(dict.Keys(0))
For i = 0 To dict.Count - 1
If dict(dict.Keys(i)) < low(2) Then
low(1) = dict.Keys(i)
low(2) = dict(dict.Keys(i))
ElseIf dict(dict.Keys(i)) > high(2) Then
high(1) = dict.Keys(i)
high(2) = dict(dict.Keys(i))
End If
Next i
Debug.Print low(1) & ":" & low(2) & vbCrLf & high(1) & ":" & high(2)
End Sub
但是这样的排序仅适用于数字值。 @Ryan Wildry的注释是对字典进行一般排序的一种方式,然后您将分别使用dict(dict.Keys(0))
引用已排序字典的dict(dict.Keys(dict.Count - 1))
和dict
来获取值。
编辑:
您需要add a library reference到Microsoft Scripting Runtime
才能正常工作。