2012-11-06 72 views
2

如何檢查用戶是否選擇了整個Excel工作表? 我曾嘗試使用以下內容。檢查整張紙是否被選中?

selection.cells.count 

但它給出了一個超出當前範圍的例外。

有沒有辦法做同樣的?

+0

VBA或C#? – nawfal

+0

2)並且你的意思是整張紙還是整張使用過的紙張? – brettdj

+2

'.CountLarge'可用於由蒂姆·威廉姆斯的Excel 2007+ –

回答

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 
3

如果你想測試UsedRange是否張玉峯到Selection然後

  1. 您需要確保UsedRange已更新
  2. 飲食中的錯誤,如果有,也無需選擇範圍

類似的部份給任何

  • 一個錯誤的警告消息(無選擇)
  • 真爲同一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 
+0

這對字符串來說很棘手。 +1 –

+0

雖然有人選擇了* Used'範圍'的想法對我來說似乎很陌生。可能交叉電線:) – brettdj

1

正如@TimWilliams在評論中指出,如果選擇整個工作表,計數溢出導致「目前所範圍」異常一個int(即Count屬性)。爲了解決這個問題,請使用CountLarge屬性。在C#中,CountLarge屬性是一個對象。要使用它,將它投射到很長時間。

long cellCount = (long)selectedRange.Cells.CountLarge; 
0

我意識到這是一個古老的討論,但我從谷歌搜索來到這裏。對於任何發現這種情況的人來說,更簡單的方法可能只是使用「.address」。例如

If Selection.address = Cells.address then Msgbox "You selected an entire sheet!" 
相關問題