这会做到这一点,但它不是一种非常优雅的做事方式 - 虽然我看不到任何替代方案。您需要利用事件来捕获先前选择的工作表。由于确定工作表上选择范围的唯一方法是激活该工作表,因此您必须关闭屏幕更新跳转到工作表,然后跳回原始工作表并重新打开屏幕更新。
将以下代码放入新模块中: Option Explicit
'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
您可以通过检查是否使用按钮停用工作表来进一步增强代码,如果是则忽略它。