vba - vba中excel列表中的最大几个变量

标签 vba excel

我有一个类似下面的列表,但行数 > 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/

相关文章:

vba - 循环工作一次,然后 "Run-time error ' 42 4': Object Required"

Excel VBA 到 Word 取消选择选定的文本

python - 异常: Exception ('Exception caught in workbook destructor. Explicit close() may be required for workbook.' ,)

Excel VBA秒表: add pause button?

excel - 发送 key 和应用程序激活

vba - 将子目录添加到动态数组

vba - Rockwell FactoryTalk View SE 上的通配符和 VBA

vba - 以编程方式删除超链接而不应用超链接样式

Excel:组合框和复选框干扰?

excel - 在文本字符串中间的货币值末尾添加 "0"