You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求实现n*2数组首列唯一值对应第二列数值求和的VBA函数

VBA Function to Summarize Unique Values with Their Corresponding Totals

Got it, let's build that VBA function you need—it'll take your n×2 input array, pull out unique values from the first column, and calculate the sum of matching values in the second column. Here's a reliable implementation using a Dictionary (it's perfect for tracking unique keys and their running totals):

Function unqfiladv(inputArr As Variant) As Variant
    Dim dict As Object
    Dim i As Long
    Dim outputArr() As Variant
    Dim key As Variant
    Dim outputRow As Long
    
    ' Initialize the Dictionary to track unique items and sums
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' Loop through the input array
    For i = LBound(inputArr, 1) To UBound(inputArr, 1)
        ' Check if the item already exists in the Dictionary
        If dict.Exists(inputArr(i, 0)) Then
            ' If it does, add the current value to the existing sum
            dict(inputArr(i, 0)) = dict(inputArr(i, 0)) + inputArr(i, 1)
        Else
            ' If not, add the item to the Dictionary with its initial value
            dict.Add inputArr(i, 0), inputArr(i, 1)
        End If
    Next i
    
    ' Resize the output array to match the number of unique items
    ReDim outputArr(0 To dict.Count - 1, 0 To 1)
    
    ' Populate the output array with unique keys and their sums
    outputRow = 0
    For Each key In dict.Keys
        outputArr(outputRow, 0) = key
        outputArr(outputRow, 1) = dict(key)
        outputRow = outputRow + 1
    Next key
    
    ' Return the final summarized array
    unqfiladv = outputArr
End Function

How this works:

  • We use a Scripting.Dictionary (a handy tool for tracking unique keys and their associated values) because it automatically enforces unique entries—perfect for capturing the distinct values from your first column.
  • As we loop through the input array, we either add a new entry to the Dictionary (for a first-time value) or add the current number to the existing sum (for repeat values).
  • Finally, we convert the Dictionary's keys and values into a properly sized n×2 output array that matches your expected structure.

Testing with your sample code:

When you run your test subroutine, the tempar array will hold exactly the results you're looking for:

  • banana | 15
  • apple | 8
  • cucumber | 12
  • a | 3

Just note that the Scripting.Dictionary is enabled by default in most Excel VBA environments, but if you run into issues, you can add a reference to "Microsoft Scripting Runtime" via Tools > References in the VBA editor.

内容的提问来源于stack exchange,提问作者user7181718

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:32:04