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

如何跨指定工作表的特定区域统计加粗且值匹配的单元格数量?

解决方案

一、改进VBA函数,直接统计指定工作表范围

1. 针对Game1到Game50连续命名的工作表

直接遍历指定命名规则的工作表,无需遍历工作簿所有表,效率更高:

Function CountBoldValueAcrossSheets(targetVal As Range) As Long
    Dim ws As Worksheet
    Dim cell As Range
    Dim wsName As String
    Dim i As Integer
    
    For i = 1 To 50
        wsName = "Game" & i
        ' 检查工作表是否存在,避免报错
        On Error Resume Next
        Set ws = ThisWorkbook.Worksheets(wsName)
        On Error GoTo 0
        
        If Not ws Is Nothing Then
            ' 遍历目标区域Q7:U269
            For Each cell In ws.Range("Q7:U269")
                If cell.Font.Bold And cell.Value = targetVal.Value Then
                    CountBoldValueAcrossSheets = CountBoldValueAcrossSheets + 1
                End If
            Next cell
            Set ws = Nothing
        End If
    Next i
End Function

使用方法:在单元格输入 =CountBoldValueAcrossSheets(A4) 即可得到总数。

2. 支持从单元格区域读取工作表名称(比如A35:A38)

如果需要灵活指定统计的工作表列表,可修改函数接收工作表名称区域参数:

Function CountBoldValueFromSheetList(sheetListRng As Range, targetVal As Range, targetArea As String) As Long
    Dim wsName As Variant
    Dim ws As Worksheet
    Dim cell As Range
    
    For Each wsName In sheetListRng.Value
        ' 检查工作表是否存在
        On Error Resume Next
        Set ws = ThisWorkbook.Worksheets(wsName)
        On Error GoTo 0
        
        If Not ws Is Nothing Then
            ' 遍历指定区域
            For Each cell In ws.Range(targetArea)
                If cell.Font.Bold And cell.Value = targetVal.Value Then
                    CountBoldValueFromSheetList = CountBoldValueFromSheetList + 1
                End If
            Next cell
            Set ws = Nothing
        End If
    Next wsName
End Function

使用方法:在单元格输入 =CountBoldValueFromSheetList(A35:A38, A4, "Q7:U269"),第三个参数为要统计的单元格区域字符串。

二、结合INDIRECT与现有VBA函数的公式方案

现有单表CountBoldValue函数可搭配INDIRECT,用SUM数组公式实现多表统计:

=SUM(COUNTIF(INDIRECT("'"&A$35:A$38&"'!Q7:U269"),A4)*N(CELL("fontbold",INDIRECT("'"&A$35:A$38&"'!Q7:U269"))))

注意:这是数组公式,Excel 2019及更早版本需按 Ctrl+Shift+Enter 确认,Excel 365/2021可直接按回车。

该方案局限:

  • CELL函数的fontbold属性在数组场景下可能出现延迟或不准确的情况
  • 工作表数量较多时,INDIRECT重复调用会导致效率低下

三、方案选型建议

  • 固定Game1到Game50的场景:优先用第一个VBA方案,效率最高且稳定
  • 需要灵活切换工作表列表的场景:选第二个VBA方案,扩展性更好
  • 禁用宏的场景:可尝试公式方案,但需注意其可靠性问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:42:37