如何检查用户是否选择了整个Excel工作表? 我试过使用以下内容。
selection.cells.count
但是它给出了目前的范围异常。
有没有办法做同样的事情?
答案 0 :(得分:3)
如果您想测试UsedRange
是否与vba中的Selection
一致,那么
UsedRange
已更新Address
字符串Address
字符串<强>码强>
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
答案 1 :(得分:1)
我将抄袭brettdj的代码并创建一个版本来测试整个工作表是否被选中。虽然我对使用字符串来包含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
答案 2 :(得分:1)
如@TimWilliams在评论中所述,如果选择整个工作表,则计数将溢出一个int(即Count
属性),导致“超出当前范围”异常。要解决此问题,请使用CountLarge
属性。在C#中,CountLarge
属性是一个对象。要使用它,将其投入很长时间。
long cellCount = (long)selectedRange.Cells.CountLarge;
答案 3 :(得分:0)
我意识到这是一个古老的讨论,但我是从谷歌搜索来到这里的。对于任何发现这一点的人来说,更简单的方法可能只是使用&#34; .address&#34;。例如
If Selection.address = Cells.address then Msgbox "You selected an entire sheet!"