检查整张纸是否被选中?
如何检查用户是否select了整个Excel工作表? 我曾尝试使用以下内容。
selection.cells.count
但它给出了一个目前的范围例外。
有没有办法做同样的事情?
我要剽窃brettdj的代码,并创build一个版本来testing整个表单是否被选中。 虽然我对使用一个string来包含TRUE,FALSE和失败值感兴趣,但我只是用一个布尔值,所以像我这样的人不会觉得太难。
Sub CheckSelection() Dim IsMatch As Boolean Dim ErrNum As Long With ActiveSheet On Error Resume Next IsMatch = (.Range(.Cells(1), .Cells(.Rows.Count, Columns.Count)).Address = Selection.Address) ErrNum = Err.Number On Error GoTo 0 If ErrNum <> 0 Then MsgBox "test failed: have you selected part of the sheet", vbCritical Else MsgBox IsMatch = True End If End With End Sub
如果你想testingUsedRange
是否与vba中的Selection
是一致的
- 您需要确保
UsedRange
已更新 - 如果没有范围select,则需要承担错误
像这样的东西给出
- 一个错误的警告信息(无select)
- 对于相同的
Address
string为真 - 假的
Address
string不同
码
Sub TestData() Dim strTest As String 'force usedrange to update ActiveSheet.UsedRange On Error Resume Next strTest = (ActiveSheet.UsedRange.Address = Selection.Address) On Error GoTo 0 If Len(strTest) = 0 Then MsgBox "test failed: have you selected part of the sheet", vbCritical Else MsgBox strTest End If End Sub
正如@TimWilliams在评论中指出的那样,如果你select了整个工作表,计数将溢出一个int(即Count
属性),导致“超出当前范围”exception。 为了解决这个问题,使用CountLarge
属性。 在C#中, CountLarge
属性是一个对象。 使用它,投它长。
long cellCount = (long)selectedRange.Cells.CountLarge;
我意识到这是一个古老的讨论,但我从谷歌search来到这里。 对于任何发现这一点的人来说,更简单的方法可能就是使用“.address”。 例如
If Selection.address = Cells.address then Msgbox "You selected an entire sheet!"