Excel VBA to check if multiple worksheets exist
Dear All,
I am working to have excel VBA that checks if multiple worksheets exist before another macro is run. Problem is that this VBA can check 1 worksheet only. Is it possible to make mySheetName to check a range(A1:A80) from Sort Order worksheet tab?
Code:
Function SheetExists(i_SheetName As String, _
Optional i_WorkbookName As String) As Boolean
Dim myWorkbook As Workbook
On Error Resume Next
'set workbook that gets checked
If i_WorkbookName = "" Then
Set myWorkbook = ActiveWorkbook
Else
Set myWorkbook = Workbooks(i_WorkbookName)
If myWorkbook Is Nothing Then Exit Function
End If
'now check if sheet exists
SheetExists = Not myWorkbook.Sheets(i_SheetName) Is Nothing
End Function
Code:
Sub Test()
Dim myWorkbookName As String
Dim mySheetName As String
myWorkbookName = "Test.xls"
'now check for the worksheet
mySheetName = "Sheet4"
If SheetExists(mySheetName, myWorkbookName) = True Then
'sheet exists
Debug.Print mySheetName & " in " & myWorkbookName & " exists."
Else
'sheet doesn't exist
MsgBox mySheetName & " in " & myWorkbookName & " doesn't exist."
End If
End Sub
Biz