Selection.SpecialCells(xlCellTypeVisible).Count 在过滤器的单行结果时给出溢出错误

问题描述

当使用 Selection.SpecialCells(xlCellTypeVisible).Count 计算过滤数据的单列时,它适用于多行结果。但是当只显示 1 行时,它会给我一个溢出错误或者我得到 count = 107564(我忘记了实际数字)。

解决方法

.Count 属于 Long 类型,但较新的 Excel 版本每个工作表的单元格(17,179,869,184 单元格)多于 Long 可以处理的数量(最大 2,147,483,647)。因此,如果您选择大量 ouf 单元格,它们会超过 Long,因此您会收到溢出错误。

要解决这个问题,您需要使用 Range.CountLarge property 而不是 Range.Count property,它的类型为 LongLong 并且可以处理如此数量的单元格。

数据类型 存储大小 范围
Long(长整型) 4 字节 -2,648 到 2,647
LongLong(LongLong 整数) 8 字节 -9,223,372,036,854,775,808 至 9,807(仅在 64 位平台上有效。)

表源:Office VBA Reference - Data type summary

这不应引发溢出错误:

Selection.SpecialCells(xlCellTypeVisible).CountLarge

有一个简单的规则:在计算行或列时 .Count 很好,但每次计算单元格(多行或多列)时,您需要确保使用 .CountLarge安全。

,

似乎如果您只选择 1 个单元格,那么 excel 会计算出工作表中的所有可见单元格。选择一个单元格并运行这一行:

Debug.Print Selection.SpecialCells(xlCellTypeVisible).Address

给了我$1:$13,$15:$17,$19:$19,$28:$37,$39:$39,$41:$52,$54:$81,$83:$1048576。使用 .Count 计算此范围内的单元格数量会导致溢出错误

这显然不是您想要的行为。作为解决方法,请尝试以下操作:

Function CountVisibleCells() As Long
    Dim rngSelection As Range
    Set rngSelection = Selection
    CountVisibleCells = 0
    If rngSelection.Cells.CountLarge > 1 Then
        CountVisibleCells = rngSelection.SpecialCells(xlCellTypeVisible).Cells.CountLarge
    ElseIf Not rngSelection.EntireRow.Hidden And _
           Not rngSelection.EntireColumn.Hidden Then
        CountVisibleCells = 1
    End If
End Function