這樣做,但這不是一種非常優雅的做事方式 - 我看不到任何替代方案。您需要利用事件才能捕獲之前選定的工作表。由於確定工作表上選擇範圍的唯一方法是激活該工作表,因此必須關閉屏幕更新跳轉到工作表,然後跳回原始工作表並重新打開屏幕更新。
將下面的代碼在一個新的模塊: 顯式的選項
'Global variables (avoid using globals if you can)
Public wsLast As Worksheet
Public iSelectedCells As Integer
'Link this sub to your button
Public Sub CountCells()
If Not wsLast Is Nothing Then
Sheets("Sheet1").Shapes("Label 1").TextFrame.Characters.Text = "There " & IIf(iSelectedCells = 1, " is " & iSelectedCells & " cell selected ", " are " & iSelectedCells & " cells selected ") & "in " & wsLast.Name
End If
End Sub
下面的代碼需要您的電子表格「的ThisWorkbook」模塊中去:
Option Explicit
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Dim wsThisWorksheet As Worksheet
'Turn off events to avoid triggering a loop
Application.EnableEvents = False
'Set this worksheet so we can come back to it
Set wsThisWorksheet = ActiveSheet
'Record the deactivated sheet as a global variable
Set wsLast = Sh
'Turn off screen updating, go back to the last sheet, count the selection
Application.ScreenUpdating = False
wsLast.Activate
iSelectedCells = Selection.Cells.Count
'Then come back to the original and turn screen updating back on
wsThisWorksheet.Activate
Application.ScreenUpdating = True
'Restore events
Application.EnableEvents = True
'Set the local variable to nothing
Set wsThisWorksheet = Nothing
End Sub
你可以進一步提高該代碼通過檢查是否使用按鈕取消激活工作表,如果是,則忽略它。
它給我這個錯誤「對象不支持此屬性或方法」 –
@MrMashabela - >查看我的編輯。它現在工作嗎? –
它仍然給我同樣的錯誤,它突出顯示這個「lngCnt = Selection.Cells.Count」黃色 –