[英]How to detect when no cell is selected while using Selection.SpecialCells(xlCellTypeVisible)?
In my Sub I'm using below code to obtain user selected range.在我的 Sub 中,我使用下面的代码来获取用户选择的范围。
Dim rng As Range
Set rng = Selection.SpecialCells(xlCellTypeVisible)
It works fine as long as user selects some cells/range.只要用户选择一些单元格/范围,它就可以正常工作。 However whenever macro is called without selecting any cells, rng overflows and application freezes.
但是,每当在未选择任何单元格的情况下调用宏时,rng 就会溢出并且应用程序会冻结。 Is there any way to detect if user hasn't selected any cells and exit safely?.
有没有办法检测用户是否没有选择任何单元格并安全退出?
Is a range selected?是否选择了范围?
If TypeOf Selection is Range Then
Does the selected range have visible cells?所选范围是否有可见单元格?
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
Final Solution that I ended Up Using我最终使用的最终解决方案
Check if selection is a range and CountLarge greater than 1;检查 selection 是否为范围且 CountLarge 是否大于 1; Use ErrorHandler to deal with cases where no visible cell is selected.
使用 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
Credits to @ BigBen for the comment and @ Tim Willams 's Answer感谢@BigBen的评论和@Tim Willams的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.