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

如何修改VBA代码正确统计电子表格内标记x的选项并输出到报表?

问题根因

你当前代码的列遍历逻辑存在边界判定问题:pc.Cells(1, Columns.Count).End(xlToLeft).Column是取pc表第一行最右侧的非空列,如果第一行在原有4个选项之后、K列之前存在空表头单元格,这个判定就会停在第5列(前4个选项的最右列),不会统计后续K到Y列的选项,这就是只能识别前4个选项的核心原因。

修复方案

推荐优先用固定列范围的写法,避免后续调整列位置又出现识别问题:

rp.Cells(1, 1) = "Modules"
rp.Cells(1, 2) = "Student Count"
rp.Cells(1, 4) = "Students registered"
rp.Cells(1, 10) = "Students registered2"   'new

nRow = 2
' 调整为遍历你实际用到的选项列,这里B列是第2列,Y列是第25列,可根据实际范围修改
For c = 2 To 25
    ' 跳过中间没有表头的空列
    If pc.Cells(1, c) <> "" Then
        rp.Cells(nRow, 1) = pc.Cells(1, c)
        rp.Cells(nRow, 2) = WorksheetFunction.CountIf(pc.Columns(c), "x")
        nRow = nRow + 1
    End If
Next c
      

rp.Cells(1, 1).CurrentRegion.Borders.LineStyle = xlContinuous
If rp.Cells(2, 4).Text <> "" Then
    rp.Cells(1, 4).CurrentRegion.Borders.LineStyle = xlContinuous
End If
rp.Rows(1).Font.Bold = True
rp.UsedRange.Columns.AutoFit

如果不想写死列范围,可以把循环终止条件替换为整个工作表的最大使用列:
For c = 2 To pc.UsedRange.Columns.Count

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 16:45:01