如何使用VBA自动拼接含空白单元格的数据
解决方案
公式方法
直接在C2单元格输入以下公式,下拉填充至所有行即可:=SUMIF(A:A,A2,B:B)
说明:SUMIF函数会匹配A列中与当前行A2相同的所有单元格,对对应的B列数值求和,最终在C列每行显示对应名称的总金额。
VBA方法
提供两种实现方式,按需选择:
方式1:批量公式写入(高效简洁)
Sub CalculateNameTotal() Dim lastRow As Long lastRow = Cells(Rows.Count, "A").End(xlUp).Row '批量写入公式 Range("C2:C" & lastRow).Formula = "=SUMIF(A:A,A2,B:B)" '若需将公式转为静态数值,取消下方注释 'Range("C2:C" & lastRow).Value = Range("C2:C" & lastRow).Value End Sub
方式2:字典循环计算(适合理解逻辑)
Sub CalculateTotalWithDict() Dim lastRow As Long, i As Long Dim totalDict As Object Set totalDict = CreateObject("Scripting.Dictionary") lastRow = Cells(Rows.Count, "A").End(xlUp).Row '先统计每个名称的总金额 For i = 2 To lastRow Dim currentName As String currentName = Cells(i, "A").Value If totalDict.Exists(currentName) Then totalDict(currentName) = totalDict(currentName) + Cells(i, "B").Value Else totalDict(currentName) = Cells(i, "B").Value End If Next i '将总金额写入C列 For i = 2 To lastRow Cells(i, "C").Value = totalDict(Cells(i, "A").Value) Next i Set totalDict = Nothing End Sub
使用步骤:打开Excel后按Alt+F11打开VBA编辑器,点击「插入」→「模块」,粘贴对应代码,按F5运行即可。
内容的提问来源于stack exchange,提问作者Sunny
相关产品推荐
相关产品推荐

