Excel VBA: Check If a Worksheet Exists
In this article
To check whether a worksheet exists in Excel VBA, loop through the Worksheets collection and compare each sheet's Name to the name you are looking for, or attempt to reference it and trap the error. The loop method is the most reliable because it avoids error handling and works the same in every Excel version. The steps below show the loop approach first, then the error-trapping alternative, with the exact code you can paste into a standard module.
What You'll Need
- Excel on Windows or Mac with the Visual Basic Editor available (Alt+F11 on Windows, Fn+Option+F11 on many Mac keyboards, or Developer > Visual Basic).
- A workbook where you are allowed to run macros. If the Developer tab is hidden, enable it via File > Options > Customize Ribbon, or just press Alt+F11.
- Macro security set to allow macros. In the Trust Center, choose "Disable all macros with notification" so you can enable them per session rather than blocking them silently.
- The exact worksheet name you want to test, including spaces and capitalisation as it appears on the tab.
Step-by-Step
- Open the Visual Basic Editor. Press Alt+F11 (Windows) or use Developer > Visual Basic. Labels in the ribbon can differ slightly by Excel version and platform, but the Visual Basic command is present in all current desktop versions.
- Insert a standard module. In the editor, choose Insert > Module. Code placed in a standard module is available to all sheets; code in a sheet module is tied to that sheet only.
- Write the loop function. Paste this into the module:
This loops through every worksheet in the workbook that contains the code.Function WorksheetExists(ByVal sheetName As String) As Boolean Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets If StrComp(ws.Name, sheetName, vbTextCompare) = 0 Then WorksheetExists = True Exit Function End If Next ws WorksheetExists = False End FunctionvbTextComparemakes the comparison case-insensitive; usevbBinaryCompareif case must match exactly. - Decide which workbook to test.
ThisWorkbookrefers to the workbook holding the macro. If you need to test a different open workbook, replace it withActiveWorkbookor a specific workbook variable such asWorkbooks("Report.xlsx"). Testing the wrong workbook is the most common reason a check returns False when the sheet is clearly visible. - Call the function from a test macro. Add a second routine:
Place the cursor insideSub TestSheet() If WorksheetExists("Summary") Then MsgBox "The sheet exists." Else MsgBox "The sheet does not exist." End If End SubTestSheetand press F5 to run it. - Read the result. A message box reports whether the name was found. If you expected True and got False, check spelling, trailing spaces and whether the sheet is in the workbook you are actually testing.
- Use the result in real code. Instead of a message box, branch on the function. For example, create the sheet only when it is missing:
This pattern prevents the run-time error 1004 that occurs when you try to add a sheet with a name that already exists.If Not WorksheetExists("Summary") Then ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)).Name = "Summary" End If - Know the error-trapping alternative. Some developers prefer to attempt a reference and catch the failure:
This is shorter but relies on error handling, which can mask unrelated problems ifFunction SheetExists2(ByVal sheetName As String) As Boolean Dim ws As Worksheet On Error Resume Next Set ws = ThisWorkbook.Worksheets(sheetName) SheetExists2 = Not ws Is Nothing On Error GoTo 0 End FunctionOn Error GoTo 0is forgotten. The loop method is easier to audit. - Save the workbook as a macro-enabled file. Use File > Save As and choose the .xlsm format. A plain .xlsx file discards the VBA project when saved.
Common Mistakes
- Testing the wrong workbook.
ThisWorkbookandActiveWorkbookare not always the same. If the macro lives in a personal workbook or an add-in,ThisWorkbookpoints there, not at the file the user is looking at. - Forgetting chart sheets.
Worksheetsdoes not include chart sheets. If a tab could be either type, loop throughSheetsinstead, which covers both. - Assuming a hidden sheet is missing. Hidden sheets are still in the
Worksheetscollection, so the loop finds them. If you want to ignore hidden sheets, add a check onws.Visible. - Case and spacing mismatches. "Summary" and "Summary " (with a trailing space) are different names. The default text comparison handles case but not stray spaces.
- Leaving error handling switched off. If you use the error-trapping version, always restore normal handling with
On Error GoTo 0after the check. - Saving as .xlsx. The code disappears on close because the format does not store macros.
Tips
- Trim input before comparing:
sheetName = Trim(sheetName)avoids failures caused by pasted names with spaces. - Keep the function in a standard module, not a sheet module, so every procedure in the project can call it.
- Name the function clearly and avoid clashing with Excel's own object names.
WorksheetExistsis safe; a name likeSheetsis not. - When creating a sheet, set the
Nameproperty immediately afterAdd, before writing any data, so later references are stable. - For large workbooks, the loop is fast enough; there is no need for a dictionary lookup unless you are checking hundreds of names in one pass.
Troubleshooting
The macro does not appear in the list. Confirm the code is in a standard module and the workbook is saved as .xlsm. If macros are disabled, close and reopen the file and click Enable Content when prompted.
The function always returns False. Check that you are testing the intended workbook and that the name matches exactly. Print the names during a test run with Debug.Print ws.Name inside the loop and compare against what you passed in.
Run-time error 1004 when adding a sheet. This usually means a sheet with that name already exists, or the name contains characters Excel does not allow (such as : \ / ? * [ ]) or exceeds 31 characters. Your existence check should run before the Add line.
Run-time error 9, subscript out of range. This comes from the error-trapping version when the sheet is missing and the error is not being handled. Make sure On Error Resume Next is in place before the reference and reset afterwards.
If that did not work, step through the code with F8 to watch each line execute, and check the Immediate Window (Ctrl+G) for printed sheet names. If the workbook is shared or protected, unshare or unprotect it first, because some operations behave differently in shared workbooks.
Frequently Asked Questions
Does this work on Excel for Mac?
Yes. The VBA editor and the Worksheets collection behave the same on current desktop versions for Mac, though the keyboard shortcut to open the editor can differ.
Can I check a sheet in a closed workbook?
Not directly with this function. You would need to open the workbook first, or use an external reference, which is slower and more fragile. Opening the file, testing, then closing it is the practical approach.
Why does the check find hidden sheets?
Hidden sheets remain part of the Worksheets collection. Only deleting a sheet removes it from the collection. Add a ws.Visible test if hidden sheets should be treated as absent.
Should I use Worksheets or Sheets?
Use Worksheets when only normal worksheets matter. Use Sheets when chart sheets could share the name space and you want to detect them too.
Is the loop or the error-trapping version faster?
Both are effectively instant for typical workbooks. The loop is easier to read and does not depend on error handling, which makes it the safer default.
Can I use this to check a sheet name before renaming?
Yes. Run the check on the proposed new name first. If it returns True, choose a different name, because renaming to an existing name raises an error.