Featured Post

Excel Macros: automating the boring stuff

Work Smarter – outsource the boring tasks to Excel Excel macros are “Excel Apps”. Some smaller, some larger, but all of them are “Apps” th...

Sunday, May 15, 2016

Activating the right sheet

Changing the active sheet given its name is one of the basic tasks when writing business macros and can be very simple with this VBA Bits library function:


SetActiveSheet (sheetname) eg: SetActiveSheet ("Sheet2")

The function is quite simple:



If the sheet exists, it will make it the active sheet (the one selected in Excel and visible to the user). If not, nothing happens, and no error is generated - it just does nothing, retaining whichever sheet is already active on the Excel file.

How does it knows if the given Sheetname exists? It uses the DoesSheetExists(“sheetname”) VBA Bits function detailed on an other post:


You can copy the code here:

Sub SetActiveSheet(sSheetName As String)
' Activates the desired sheet by name if the sheet exists
Dim bOut As Boolean                                                     ' Declare the variables

    bOut = False                                                        ' Default - Assume Failure
    If DoesSheetExists(sSheetName) Then Worksheets(sSheetName).Activate ' Activate sheet with given name if it exists

End Sub

No comments:

Post a Comment