The following code gets user back to the old sheet if a Chart
is activated, and it shows how many data points are included in the Chart
before getting back. And I wonder why the variable Sh
is defined as Object
rather than Sheet
in the two event-handler procedures. Same for the variable OldSheet
.
Dim OldSheet As Object
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Set OldSheet = Sh
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim Msg As String
If TypeName(Sh) = "Chart" Then
Msg = "This chart contains "
Msg = Msg & ActiveChart.SeriesCollection(1).Points.Count
Msg = Msg & " data points." & vbNewLine
Msg = Msg & "Click OK to return to " & OldSheet.Name
MsgBox Msg
OldSheet.Activate
End If
End Sub
Notice the event is SheetActivate
, not WorksheetActivate
- the concept of a "sheet" encompasses several types that have nothing in common, other than the ability to be "activated". There is no Sheet
type in the Excel object model - the Workbook.Sheets
collection contains various types of objects, including Chart
and Worksheet
objects.
The Sh
parameter in the SheetActivate
event has to be an Object
, because there is no common interface between a Chart
and a Worksheet
.
So you need do what you did: verify the type of the object instead of assuming you're dealing with a Chart
or a Worksheet
object.
Instead of using the TypeName
function and thus stringly-typed type checks, you should use the TypeOf
operator instead:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If TypeOf Sh Is Excel.Worksheet Then
Debug.Print "Worksheet!"
ElseIf TypeOf Sh Is Excel.Chart Then
Debug.Print "Chart!"
Else
Debug.Print "Something else!"
End If
End Sub
The parameter being Object
allows future versions to activate a "sheet" of a type that couldn't be dreamed of at the time the event declaration was written in the IWorkbookEvents
hidden interface that every Workbook
object implements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With