VBA 按名称从大到小列出参数

VBA list arguments by their name from largest to lowest

我正在尝试评估不同参数的值并从最大到最低获取排序列表,但显示为参数名称。到目前为止,我所拥有的是一个简单的 MAX 函数,它 returns 最大值。

Result = Application.Max(Chicago_SantaFe, Vancouver_SantaFe, Calgary_SaltLakeCity)

Result_Label.caption = Result

如您所见,我在 MAX 函数中的参数是“Chicago_SantaFe、Vancouver_SantaFe、Calgary_SaltLakeCity” 所以结果会是这样的:

Chicago_SantaFe Vancouver_SantaFe Calgary_SaltLakeCity

有人可以回答这个问题吗?

一种方法是在变量和变量名之间建立一个映射。 然后按值排序并输出名称。

这是一种假设没有重复项(具有相同值的两个变量)的方法。如果不是这种情况,可以很容易地修改代码。

因为你没有说明你是如何给变量赋值的,我只是直接这样做了,但你可以用你的方法代替。

Option Explicit
Sub due()
    Const Chicago_SantaFe As Long = 1
    Const Vancouver_SantaFe As Long = 7
    Const Calgary_SaltLakeCity As Long = 3
    Dim v As Variant, w As Variant, s As String
    
Dim myDict As Object
Dim AL As Object
Set myDict = CreateObject("Scripting.Dictionary")

myDict.Add Key:=Chicago_SantaFe, Item:="Chicago_SantaFe"
myDict.Add Key:=Vancouver_SantaFe, Item:="Vancouver_SantaFe"
myDict.Add Key:=Calgary_SaltLakeCity, Item:="Calgary_SaltLakeCity"

'Use arraylist for sorting
Set AL = CreateObject("System.Collections.ArrayList")

For Each v In myDict.keys
    AL.Add v
Next v

AL.Sort
AL.Reverse

For Each v In AL
    s = s & vbLf & myDict(v)
Next v

MsgBox Mid(s, 2)

End Sub

如果您的变量可能有重复值,并且要在有更多变量的地方使用例程,您可以使用类似下面的方法,其中您

  • 制作两个数组
    • 其中一个变量值
    • 另一个变量名
  • 遍历两个数组以创建映射
  • 不是只将变量名称存储为项目,而是存储与特定值关联的变量名称的集合

然后,对于输出,你

  • 对键进行排序
  • 遍历每个键存储的集合
Option Explicit
Sub due()
    Const Chicago_SantaFe As Long = 1
    Const Vancouver_SantaFe As Long = 7
    Const Calgary_SaltLakeCity As Long = 3
    Const Nome_Fairbanks As Long = 3
    Dim v As Variant, w As Variant, s As String, col As Collection
    Dim I As Long
    
v = Array(Chicago_SantaFe, Vancouver_SantaFe, Calgary_SaltLakeCity, Nome_Fairbanks)
w = Array("Chicago_SantaFe", "Vancouver_SantaFe", "Calgary_SaltLakeCity", "Nome_Fairbanks")
    
Dim myDict As Object
Dim AL As Object
Set myDict = CreateObject("Scripting.Dictionary")

For I = LBound(v) To UBound(v)
    If Not myDict.exists(v(I)) Then
        Set col = New Collection
        col.Add w(I)
        myDict.Add Key:=v(I), Item:=col
    Else
        myDict(v(I)).Add w(I)
    End If
Next I

'Use arraylist for sorting
Set AL = CreateObject("System.Collections.ArrayList")

For Each v In myDict.keys
    AL.Add v
Next v

AL.Sort
AL.Reverse

For Each v In AL
    For Each w In myDict(v)
        s = s & vbLf & w
    Next w
Next v

MsgBox Mid(s, 2)

End Sub