检查是否选择了整张纸?

时间:2012-11-06 04:50:14

标签: c# excel visual-studio excel-vba vsto vba

如何检查用户是否选择了整个Excel工作表? 我试过使用以下内容。

selection.cells.count

但是它给出了目前的范围异常。

有没有办法做同样的事情?

4 个答案:

答案 0 :(得分:3)

如果您想测试UsedRange是否与中的Selection一致,那么

  1. 您需要确保UsedRange已更新
  2. 如果没有范围选择,也需要照顾错误
  3. 像这样的东西

    • 错误警告消息(无选择)
    • 对于相同的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!"