Option Explicit
' Provide the ability to create a Back button to return to the
' previously active sheet
' This code uses a class with state that tracks sheet changes for all
' open workbooks. If the VBA code is stopped (such as if an unhandled error
' occurs and the user hits End, or a developer clicks the Stop button
' in the VBA development window) then the tracker object is destroyed
' and will have to be started again. Note that this is done automatically
' on a failed attempt to go to the last sheet, but past information is lost.
Dim SheetTracker As New ClassSheetChangeTracker
' This instantiates the class used to track sheet navigation so
' must be called when this workbook is opened
Public Sub StartSheetTracker()
Set SheetTracker.appevent = Application
End Sub
' Add a button to the Ribbon or the Quick Access Toolbar that references
' this sub to return to the previously active worksheet
Public Sub GoToLastSheet()
On Error GoTo CannotDoIt
' An error will occur if the SheetTracker is not instantiated, or
' it cannot find the previous active sheet for the workbook
SheetTracker.LastSheet(WorkbookName:=ActiveWorkbook.Name).Activate
Exit Sub
CannotDoIt:
If SheetTracker Is Nothing Then
MsgBox "Sheet tracker not found, restarting"
StartSheetTracker
Else
MsgBox "Unable to determine previous sheet for " & ActiveWorkbook.Name
End If
End Sub