Excel VBA – sorting值和variables

如果你有variables和值在vba是可能的sorting他们从最大到最小,而且还与variables相匹配。 所以例如,如果你有VBA:

Sub sort() ... x = 5 y = 3 z = 8 ... End sub 

在Excel中你得到(在A列variables,在B列值):

  AB z 8 x 5 y 3 

对8,5,3进行sorting非常简单,但如何将z,x,y添加到适当的位置?

AFAIK没有任何方法来完成你所要求的。 variables名称是您的代码的一部分; 使用和访问它们作为数据将需要反映 ,这不是Excel VBA提供的*。

但我不认为你所要求的是实现长期目标的最好方法。 您似乎需要的是一种存储(名称,值)对并访问名称和值的方法。 一个简单的方法是使用Dictionary对象。

如果你需要不同的function,还有其他的select,例如使用一对数组(一个保存名字,一个保存数值) – 为了使这个更加整洁,你可以写一个类来保持这两个数组的一致性,并实现你需要的任何函数方法。

一旦你有(姓名,价值)对输出他们在一个sorting列表是直截了当的。 最简单的方法是将它们写入电子表格,然后使用Excel的内置Range.Sort (请参阅MSDN文档 )。

把它放在一起(注意这需要对Dictionary对象的Microsoft Scripting Runtime库的引用):

 Dim dict As New Dictionary Dim ws As Worksheet, rng As Range Dim ky As Variant, itm As Variant Set ws = ThisWorkbook.Worksheets(1) 'Add items to dictionary dict.Add "x", 5 dict.Add "y", 3 dict.Add "z", 8 'You can use these in code like this: For Each ky In dict.Keys Debug.Print "The value of " & ky & " is " & dict(ky) Next ky 'you can change values dict.item("z") = 10 dict.item("z") = 8 'Output the values and keys (the key/value arrays are horizontal while 'the range is vertical, hence transpose) Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(dict.Count, 2)) rng.Columns(1).Value = Application.Transpose(dict.Keys) rng.Columns(2).Value = Application.Transpose(dict.Items) 'Sort them rng.Sort Key1:=ws.Range("B1"), Header:=xlNo 

*不容易 – 有一些对象可以通过VBProject访问代码。 但是用它来做你所要求的就不可能了。

在VBA中不存在variables之间的顺序。 你可以确定x是否大于y,但是这并不能帮助你,因为你需要按照特定的顺序。
我的回答并不完全是你所要求的,但我怀疑它会帮助你。
既然你已经把你的输出结果输出到了表单中,尽pipe未sorting,那么在那里sorting就更容易了。 简单地将列A和B与列B一起分类为主要的。
在代码中这样做有点复杂。 您需要将名称(x,y,z)和值(8,5,3)放在数组中,然后对数组进行sorting。 如何对数组进行sorting已经被描述了几次(如: Excel VBA按照降序对数组进行sorting的最快方法? )