You need to enable JavaScript to run this app. Excel VBA实现两列交叉引用计数并输出到其他工作表
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA实现两列交叉引用计数并输出到其他工作表

Excel交叉分类计数实现方案

方案1:VBA自定义输出

以下代码可直接实现O列唯一值对应U列两类计数的统计,结果输出到指定工作表:

Sub CountByType()
    Dim sourceSht As Worksheet, targetSht As Worksheet
    Dim countDict As Object
    Dim lastRow As Long, oCol As Long, uCol As Long, outputStartRow As Long
    Dim oVal As String, uVal As String
    
    ' 可修改配置项
    Set sourceSht = ThisWorkbook.Worksheets("你的原始数据表名") ' 替换为实际源表名
    Set targetSht = ThisWorkbook.Worksheets("你的结果表名") ' 替换为实际输出表名
    oCol = 15 ' O列对应列号为15,示例中对应A列则修改为1
    uCol = 21 ' U列对应列号为21,示例中对应B列则修改为2
    outputStartRow = 2 ' 结果从输出表第2行开始写入(第1行留作表头)
    
    ' 初始化字典存储唯一值与对应计数
    Set countDict = CreateObject("Scripting.Dictionary")
    lastRow = sourceSht.Cells(sourceSht.Rows.Count, oCol).End(xlUp).Row
    
    ' 遍历源表统计
    For i = 2 To lastRow ' 假设源表第1行是表头,跳过表头从第2行读取
        oVal = Trim(sourceSht.Cells(i, oCol).Value)
        uVal = LCase(Trim(sourceSht.Cells(i, uCol).Value))
        If oVal <> "" And (uVal = "paper" Or uVal = "electronic") Then
            If Not countDict.Exists(oVal) Then
                countDict(oVal) = Array(0, 0) ' 数组第0位存paper计数,第1位存electronic计数
            End If
            If uVal = "paper" Then
                countDict(oVal) = Array(countDict(oVal)(0) + 1, countDict(oVal)(1))
            Else
                countDict(oVal) = Array(countDict(oVal)(0), countDict(oVal)(1) + 1)
            End If
        End If
    Next i
    
    ' 输出表头
    targetSht.Cells(1, 1) = "O列取值"
    targetSht.Cells(1, 2) = "paper计数"
    targetSht.Cells(1, 3) = "electronic计数"
    targetSht.Cells(1, 4) = "总计数"
    
    ' 输出统计结果
    outputRow = outputStartRow
    For Each key In countDict.Keys
        targetSht.Cells(outputRow, 1) = key
        targetSht.Cells(outputRow, 2) = countDict(key)(0)
        targetSht.Cells(outputRow, 3) = countDict(key)(1)
        targetSht.Cells(outputRow, 4) = countDict(key)(0) + countDict(key)(1)
        outputRow = outputRow + 1
    Next key
    
    ' 可选:自动调整列宽
    targetSht.Columns("A:D").AutoFit
    MsgBox "统计完成,共匹配" & countDict.Count & "个O列唯一值"
End Sub

使用说明:按Alt+F11打开VBA编辑器,插入模块粘贴代码,修改上方配置项后运行即可

方案2:零代码实现(无需VBA)

你之前使用数据透视表无法实现交叉统计是字段布局错误导致,按以下操作即可直接生成结果:

  • 选中全表数据插入数据透视表
  • 行字段区域拖入O列字段
  • 值字段区域拖入两次U列字段,分别对两个值字段设置筛选,仅统计值为paper和electronic的计数
  • 也可直接使用COUNTIFS函数实现,公式模板:
    • paper计数:=COUNTIFS(O:O,"目标O列值",U:U,"paper")
    • electronic计数:=COUNTIFS(O:O,"目标O列值",U:U,"electronic")

更优数据呈现建议

  • 统计结果新增占比列:paper占比=paper计数/总计数,可直观查看不同O列取值的文档类型分布
  • 如需可视化可基于统计结果插入堆叠柱状图,可快速对比不同取值的两类数量差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 16:15:04