我有两个值的变量:
V11|63|40
V22|12|6
V09|80|20
我的目标是执行以下操作:
对于每个变量,从第一个值中减去第二个值。对结果进行排序,并使用变量名返回前两个结果。
在这种情况下:
V09|60
V11|23
我开始用数组解决这个问题,但是数组只能保存相同数据类型的值,因此变量名会产生一些问题。 我试过字典,但只能容纳一个键和一个值(我一听说)。谁能告诉我什么是一个好的收集对象来执行我想要的?
答案 0 :(得分:0)
此答案适用于一个工作表,但我相信您可以针对多个工作表调整此代码。
Sub substrSort()
Dim startColumn As Integer, startRow As Integer
startColumn = 2 'Column with names is B
startRow = 3 'Row with first variable is 3
Const numOfEntries As Integer = 3 'count of variables
Dim varnames(numOfEntries - 1) As String
Dim results(numOfEntries - 1) As Integer
Dim resultsSorted(1) As Integer '2 entries
Dim namesSorted(1) As String '2 entries
namesSorted(0) = ""
namesSorted(1) = ""
Dim i As Integer
Dim tmpA As Integer, tmpB As Integer
For i = 0 To numOfEntries - 1
varnames(i) = ActiveSheet.Cells(startRow + i, startColumn)
tmpA = ActiveSheet.Cells(startRow + i, startColumn + 1)
tmpB = ActiveSheet.Cells(startRow + i, startColumn + 2)
results(i) = tmpA - tmpB
Next i
For i = 0 To numOfEntries - 1
If results(i) > resultsSorted(0) Then
resultsSorted(1) = resultsSorted(0)
resultsSorted(0) = results(i)
namesSorted(1) = namesSorted(0)
namesSorted(0) = varnames(i)
ElseIf results(i) > resultsSorted(1) Then
resultsSorted(1) = results(i)
namesSorted(1) = varnames(i)
End If
Next i
ActiveSheet.Cells(startRow, startColumn + 5) = namesSorted(0)
ActiveSheet.Cells(startRow, startColumn + 6) = resultsSorted(0)
ActiveSheet.Cells(startRow + 1, startColumn + 5) = namesSorted(1)
ActiveSheet.Cells(startRow + 1, startColumn + 6) = resultsSorted(1)
End Sub
一些解释: