我有一个类似下面的列表,但行数 > 100k。我想找到列表中每个字母的最大值。需要 vba 中的解决方案而不是工作表函数。
字母值
答:100
B. 200
C. 300
答:250
B. 150
答:200
C. 350
最佳答案
最好的方法是使用 Dictionary
目的。下面是介绍如何实现它的代码(代码内的注释):
Public Sub findMaxValues()
Dim wks As Excel.Worksheet
Dim data As Variant
Dim dict As Object
Dim row As Long
Dim letter As String
Dim value As Double
'---------------------------------------------------------
Dim varKey As Variant
'---------------------------------------------------------
'Read the data into array (for better performance).
'I assumed that data starts in the cell A1 of the currently active worksheet. If not,
'change the code below properly.
Set wks = Excel.ActiveSheet
data = wks.Cells(1, 1).CurrentRegion
Set dict = VBA.CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
'Iterate through all the rows of the array (start from the second row to skip headers).
For row = LBound(data, 1) + 1 To UBound(data, 1)
letter = VBA.Trim(data(row, 1))
value = data(row, 2)
'For each row check if the letter assigned to this row has been already added to the dictionary.
If dict.Exists(letter) Then
'If letter has been added before, check if the current value is greater than the previous one
'and override it, if it is.
If value > dict.Item(letter) Then
dict.Item(letter) = value
End If
Else
'If letter has not been added to the dictionary before, add it with the current value.
Call dict.Add(letter, value)
End If
Next row
'At this point, we have dictionary with as many items as many letters are in the worksheet.
'Each item has a letter as a key and this letter's max value as a value.
'To check it, let's print it in Immediate window.
For Each varKey In dict.Keys
Debug.Print varKey & ": " & dict.Item(varKey)
Next varKey
End Sub
关于vba - vba中excel列表中的最大几个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34132817/