【问题标题】:Selection.SpecialCells(xlCellTypeVisible).Count gives overflow error when single row result from filterSelection.SpecialCells(xlCellTypeVisible).Count 在过滤器产生单行结果时给出溢出错误
【发布时间】:2023-03-29 03:52:01
【问题描述】:

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

【问题讨论】:

  • 你能分享更多的代码吗?只需重新运行宏以获取确切的错误消息 - 错误消息是什么?另外,您确定选择了任何可见的单元格吗?

标签: excel vba selection


【解决方案1】:

似乎如果您只选择 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

【讨论】:

  • 其实这并不能解决问题。如果所选单元格的数量超过2,147,483,647,这仍然会溢出!这在您的代码中仍然是可能的,因为 Excel 每个工作表都有 17,179,869,184 单元格。请参阅我的答案以获得解释。
  • @Pᴇʜ 我只是在输入:D。如果 rngSelection 的单元数超过 count 可以处理的数量,If rngSelection.Cells.Count > 1 Then 行将失败
  • @Pᴇʜ 将其更改为 CountLarge。正如你所说,使用它没有害处。更奇怪的是,如果工作表中没有隐藏的行/列,并且您只选择了一个单元格,那么 Selection.SpecialCells(xlCellTypeVisible) 会产生预期的一个单元格:非常奇怪 :) 无论如何,我很高兴你明白了我的意思。跨度>
  • 那就更奇怪了。我无法解释这种行为,对我来说它看起来既无用也不遵循任何逻辑。但我可以确认它,对我来说它看起来像一个错误。但不是第一个,只是一长串“VBA 的奇怪行为” 中的另一个;)
  • 非常感谢你们!我会试试看它是否有效。
【解决方案2】:

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

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

Data type Storage size Range
Long (Long integer) 4 bytes -2,147,483,648 to 2,147,483,647
LongLong (LongLong integer) 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (Valid on 64-bit platforms only.)

表格来源:Office VBA Reference - Data type summary.

这不应引发溢出错误:

Selection.SpecialCells(xlCellTypeVisible).CountLarge

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2020-04-01
    • 2020-01-16
    • 2023-03-25
    • 1970-01-01
    • 2013-12-10
    相关资源
    最近更新 更多