Use this function (which you can also pass a workbook variable to) to determine if a sheet exists (sourced from this solution):
Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
WorksheetExists = Not sht Is Nothing
End Function
You can call this function from your macro to dynamically assign your sheet. A few things to note here:
- If more than one of your target sheets exist, the code will assign your sheet variable to the first one that hits a match
- You may want to account for the possibility that none of the sheets exist
Sub Test()
Dim ws As Worksheet
'Dynamically assign worksheet variable
If WorksheetExists("Sheet1") Then
Set ws = Sheets("Sheet1")
ElseIf WorksheetExists("Sheet2") Then
Set ws = Sheets("Sheet2")
ElseIf WorksheetExists("Sheet3") Then
Set ws = Sheets("Sheet3")
End If
'Account for none of the sheets existing
If ws Is Nothing Then
MsgBox "None of sheets exist"
Exit Sub
End If
MsgBox ws.Name
End Sub