【问题标题】:How to detect when no cell is selected while using Selection.SpecialCells(xlCellTypeVisible)?如何在使用 Selection.SpecialCells(xlCellTypeVisible) 时检测何时未选择任何单元格?
【发布时间】:2021-08-20 00:47:23
【问题描述】:

在我的 Sub 中,我使用下面的代码来获取用户选择的范围。

Dim rng As Range
Set rng = Selection.SpecialCells(xlCellTypeVisible)

只要用户选择一些单元格/范围,它就可以正常工作。但是,每当在未选择任何单元格的情况下调用宏时,rng 就会溢出并且应用程序会冻结。有什么方法可以检测用户是否没有选择任何单元格并安全退出?

【问题讨论】:

  • 为什么不使用Application.InputBox 来提示用户选择范围?您可以将.SpecialCells 与结果一起使用,而不是依赖Selection
  • 您的代码在Set rng = 行失败?我只是在测试用例中隐藏了我选择的行(使其“不可见”),然后尝试了您的代码并立即执行。我添加了Msgbox Rng.Address,它返回了$2:$1048576,所以如果选择被隐藏,你肯定会有很大的范围,但我没有崩溃。我觉得我们在这里遗漏了一些重要的代码。
  • 我第二个@K.Dᴀᴠɪs。隐藏一些单元格,然后只选择 一个 可见单元格,选择工作表中的所有可见单元格,一直到最后一行/列。在测试SelectionRange 之后,您可能还想测试Selection.CountLarge > 1

标签: excel vba error-handling


【解决方案1】:

是否选择了范围?

If TypeOf Selection is Range Then

所选范围是否有可见单元格?

On Error Resume Next 'ignore error if there are no visible cells in the selected range
Set rng = Selection.SpecialCells(xlCellTypeVisible)
On Error Goto 0      'stop ignoring errors

If Not rng Is Nothing then
   'do something with rng
End If

【讨论】:

    【解决方案2】:

    我最终使用的最终解决方案

    检查 selection 是否是一个范围并且 CountLarge 是否大于 1 ;使用 ErrorHandler 处理没有选择可见单元格的情况。

    If TypeOf Selection Is Range And Selection.CountLarge > 1 Then
        On Error GoTo ErrorHandler
        Set rng = Selection.SpecialCells(xlCellTypeVisible)
        On Error GoTo 0
    'other bits of code
    Else
    ErrorHandler: 
    'Inform user that macro only works with 2 or more visible cells selected
    End If
    

    @comment 和@Tim WillamsAnswer 的致谢@BigBen

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      • 2021-08-24
      • 2015-04-10
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2020-02-18
      相关资源
      最近更新 更多