请尝试下一个代码。它需要对“Microsoft 脚本运行时”的引用。我也贴一段代码,可以自动添加:
Sub sumUniqueConcatenatedCases()
Dim sh As Worksheet, sh1 As Worksheet, lastR As Long
Dim arr, arrFin, arrKey, i As Long, dict As New Scripting.Dictionary
Set sh = ActiveSheet
Set sh1 = sh.Next 'you can use here a sheet you need (to return the procesed data)
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row 'last row of A:A column
arr = sh.Range("A2:C" & lastR).Value 'place the range in an array for faster iteration
For i = 1 To UBound(arr) 'iterate between the array elements
If Not dict.Exists(arr(i, 1) & "|" & arr(i, 2)) Then 'if not in dictionary:
dict.Add arr(i, 1) & "|" & arr(i, 2), arr(i, 3) 'create the key with value from C:C as item
Else
dict(arr(i, 1) & "|" & arr(i, 2)) = dict(arr(i, 1) & "|" & arr(i, 2)) + arr(i, 3) 'add C:C value to existing item value
End If
Next i
ReDim arrFin(1 To dict.count, 1 To 3) 'reDim the final array in order to keep the dictionary keys and necessary values
'Place the processed values in final array (arrFin):
For i = 0 To dict.count - 1
arrKey = Split(dict.Keys(i), "|") 'split the key, to extract the first two columns strings
arrFin(i + 1, 1) = arrKey(0): arrFin(i + 1, 2) = arrKey(1) 'place the extracted strings in arrFin
arrFin(i + 1, 3) = dict.items(i) 'place the item in the third column
Next
'drop the processed array result (in the next sheete) at once:
sh1.Range("A2").Resize(UBound(arrFin), UBound(arrFin, 2)).Value = arrFin
MsgBox "Ready..."
End Sub
它将在下一张表中返回处理后的结果。如果下一张不方便,退货单应该很容易适应您的需要。但是,这样的下一张纸必须存在...
要自动添加必要的引用,请运行以下代码:
Sub addScrRunTimeRef()
'Add a reference to 'Microsoft Scripting Runtime':
'In case of error ('Programmatic access to Visual Basic Project not trusted'):
'Options->Trust Center->Trust Center Settings->Macro Settings->Developer Macro Settings->
' check "Trust access to the VBA project object model"
On Error Resume Next
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\SysWOW64\scrrun.dll"
If err.Number = 32813 Then
err.Clear: On Error GoTo 0
MsgBox "The reference already exists...": Exit Sub
Else
On Error GoTo 0
MsgBox """Microsoft Scripting Runtime"" reference added successfully..."
End If
End Sub
运行此代码,保存工作簿(以保留将来的参考),然后再运行上述代码。
代码可以设计成不需要这样的引用,但最好有智能感知建议,什么时候自己尝试使用字典。
请进行测试并发送一些反馈。
并且,请注意,下次提问时,您应该证明您至少做过研究。最好的方法是向我们展示一段代码,即使它不能满足您的需求......