Excel does not provide a built-in way to return to the previously active worksheet. This VBA provides a method for doing this.
To use this solution, install the following code into the PERSONAL.xlsb workbook. There are three pieces of code that must be copied into three different places:
Create a new standard module with any name, and copy this code into it:
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
Create a new class called ClassSheetChangeTracker and paste the following code into it:
Option Explicit
Public WithEvents appevent As Application
Dim PreviousSheets As scripting.Dictionary
Private Sub Class_Initialize()
Set PreviousSheets = CreateObject("Scripting.Dictionary")
End Sub
' This is an event callback function that will be called
' any time that a sheet in any open workbook is deactivated
Private Sub appevent_SheetDeactivate(ByVal Sh As Object)
If PreviousSheets.Exists(key:=Sh.Parent.Name) Then
PreviousSheets.Remove key:=Sh.Parent.Name
End If
PreviousSheets.Add key:=Sh.Parent.Name, Item:=Sh
'MsgBox "Left sheet " & Sh.Name
End Sub
Property Get LastSheet(WorkbookName As String) As Worksheet
Set LastSheet = PreviousSheets(key:=WorkbookName)
End Property
Add the following sub into the ThisWorksheet module. If you already have a sub called Workbook_Open in that module, add the line of code shown.
Option Explicit
Private Sub Workbook_Open()
SheetTracking.StartSheetTracker
End Sub
Bookmarks