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

VBA条件求和问题:如何排除Pending状态的任务项分类求和

解决方法

原代码仅通过SumIf实现单条件分类求和,要排除Status为Pending的项,需改用支持多条件筛选的SumIfs函数,同时调整参数顺序(SumIfs需先指定求和区域,再依次列出条件区域与对应条件)。

修改后的完整代码:

Sub InventoryCounts()
    Dim ws As Worksheet
    Set ws = ActiveSheet

    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    Dim uniqueCategories As Object
    Set uniqueCategories = CreateObject("Scripting.Dictionary")

    Dim cell As Range
    ' 收集所有唯一分类
    For Each cell In ws.Range("E2:E" & lastRow)
        If Not uniqueCategories.Exists(cell.Value) Then
            uniqueCategories.Add cell.Value, 0
        End If
    Next cell

    Dim category As Variant
    Dim sumResult As Double
    Dim outputRow As Long
    outputRow = 2 ' 结果从第2行开始输出(第1行是表头)

    ' 写入表头
    With Worksheets("Sheet1")
        .Range("A1") = "分类"
        .Range("B1") = "有效任务项总数"
    End With

    ' 遍历每个分类,计算排除Pending后的求和结果
    For Each category In uniqueCategories.Keys
        ' 使用SumIfs:求和区域G列,条件1:E列匹配当前分类,条件2:B列不等于"Pending"
        sumResult = Application.WorksheetFunction.SumIfs( _
            ws.Range("G2:G" & lastRow), _
            ws.Range("E2:E" & lastRow), category, _
            ws.Range("B2:B" & lastRow), "<>Pending" _
        )

        ' 输出结果到Sheet1
        With Worksheets("Sheet1")
            .Cells(outputRow, "A").Value = category
            .Cells(outputRow, "B").Value = sumResult
        End With
        outputRow = outputRow + 1
    Next category
End Sub

关键修改说明

  • 替换SumIf为SumIfs,实现多条件求和逻辑
  • 新增筛选条件:ws.Range("B2:B" & lastRow), "<>Pending",直接排除Status为Pending的行
  • 用With语句简化对Sheet1的重复操作,提升代码可读性
  • 调整表头文字更贴合业务场景(可根据需求自行修改)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 08:27:35