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 8, 2016

Testing if a sheet exists on the Excel file, given its name


DoesSheetExists (“sheetname”) eg: DoesSheetExists ("Sheet2")


Checking if a given sheet exists having its name is simple - iterate all existing sheets and compare each one’s name with the given one. If a match is found, the function returns a TRUE value to its called. If not, FALSE is returned and no sheet with the given name was found.



The sSheetName variable is a function parameter, supplied between () after the function name. Is is a string (text) and can either be a literal text ("Sheet1") or a variable from existing code - examples of this will be found on the next VBA Bits post, which uses this function.

The UPPER() function forces text to be uppercase, assuring the comparison is not case dependent, which is how Excel treats Worksheet names.

You can copy the code here:


Function DoesSheetExists(sSheetName As String) As Boolean
' Checks if a Sheet name exists - Returns TRUE or FALSE
Dim bOut As String, WSN As Worksheet                    ' Declare the variables

    bOut = False                                        ' Default - Assume Failure
    For Each WSN In Worksheets                          ' Loop all worksheets in current file
        If UCase(sSheetName) = UCase(WSN.Name) Then     ' Compare each sheet name with the supplied one
            bOut = True                                 ' Name Found
            Exit For                                    ' Exit loop - already found the sheet name
        End If
    Next                                                ' Loop until all sheets checked

DoesSheetExists = bOut                                  ' Return result to caller

End Function



No comments:

Post a Comment