簡體   English   中英

如何在使用 Selection.SpecialCells(xlCellTypeVisible) 時檢測何時未選擇任何單元格?

[英]How to detect when no cell is selected while using Selection.SpecialCells(xlCellTypeVisible)?

在我的 Sub 中,我使用下面的代碼來獲取用戶選擇的范圍。

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

只要用戶選擇一些單元格/范圍,它就可以正常工作。 但是,每當在未選擇任何單元格的情況下調用宏時,rng 就會溢出並且應用程序會凍結。 有沒有辦法檢測用戶是否沒有選擇任何單元格並安全退出?

是否選擇了范圍?

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

我最終使用的最終解決方案

檢查 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

感謝@BigBen評論和@Tim Willams回答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM