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

Excel跨工作表VBA COUNTIF多条件统计语句咨询

在VBA中统计多条件记录数的可行方案

COUNTIF仅支持单条件统计,你需要的双条件统计得用COUNTIFS函数。下面提供两种通用的VBA实现方式,适配不同的数据结构:

方法一:基于普通区域(通过列标题定位,适配列位置变动)

这种方法会自动查找目标列的位置,不用担心后续列顺序调整导致代码失效:

Sub CountOutstandingSubstationJobs()
    Dim wsData As Worksheet
    Dim wsResult As Worksheet
    Dim infoCol As Long, jobDescCol As Long
    Dim lastRow As Long, countResult As Long
    
    ' 替换为你的数据所在工作表名
    Set wsData = ThisWorkbook.Worksheets("DataSheet")
    ' 替换为你要输出结果的工作表(比如当前活动表)
    Set wsResult = ThisWorkbook.ActiveSheet
    
    ' 查找目标列的列号
    On Error Resume Next
    infoCol = wsData.Rows(1).Find(What:="Info Received", LookIn:=xlValues, LookAt:=xlWhole).Column
    jobDescCol = wsData.Rows(1).Find(What:="Job Description", LookIn:=xlValues, LookAt:=xlWhole).Column
    On Error GoTo 0
    
    ' 检查列标题是否存在
    If infoCol = 0 Or jobDescCol = 0 Then
        MsgBox "未找到指定列标题,请检查工作表", vbExclamation
        Exit Sub
    End If
    
    ' 获取数据区域最后一行
    lastRow = wsData.Cells(wsData.Rows.Count, infoCol).End(xlUp).Row
    
    ' 用COUNTIFS统计双条件记录
    countResult = Application.WorksheetFunction.CountIfs( _
        wsData.Range(wsData.Cells(2, infoCol), wsData.Cells(lastRow, infoCol)), "Outstanding", _
        wsData.Range(wsData.Cells(2, jobDescCol), wsData.Cells(lastRow, jobDescCol)), "Substation Location" _
    )
    
    ' 输出结果到指定单元格
    wsResult.Range("A1").Value = "符合条件的记录数:"
    wsResult.Range("B1").Value = countResult
    ' 同时在即时窗口输出
    Debug.Print "统计结果:" & countResult
End Sub

方法二:基于结构化数据表(ListObject)

如果你的数据是Excel结构化表(插入的表格),可以直接引用表列,代码更简洁:

Sub CountFromStructuredTable()
    Dim tbl As ListObject
    Dim countResult As Long
    
    ' 替换为你的数据表所在工作表名和表名
    Set tbl = ThisWorkbook.Worksheets("DataSheet").ListObjects("JobDataTable")
    
    ' 直接通过表列名统计
    countResult = Application.WorksheetFunction.CountIfs( _
        tbl.ListColumns("Info Received").DataBodyRange, "Outstanding", _
        tbl.ListColumns("Job Description").DataBodyRange, "Substation Location" _
    )
    
    MsgBox "符合条件的记录数:" & countResult
End Sub

注意事项

  • 替换代码中的工作表名、表名为你的实际名称;
  • 确保列标题完全匹配(默认不区分大小写,但建议和工作表内的列名一致);
  • 如果不需要输出到单元格,直接用countResult变量的值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:33:28