0
votes

I am trying to only run a set of macros if a sheet doesn't already exist. I have a macro that creates a sheet and combines data from two sheets into it, and another that formats the new sheet. Since it needs to run on workbook open, I can't have it recreating the sheet again and again. I have been trying the following, but it gives the error: "sub or Function not defined":

Private Sub Workbook_Open()
If SheetExist("MyNewSheet") Then
End Sub
Else
Combine
Format
End Sub
2
Yea, the problem is "End Sub" should be "Exit Sub" You can also use the solution below. If SheetExist("MyNewSheet") Then Exit Sub - user1274820

2 Answers

2
votes

You aren't doing anything if the sheet exists, so change your test.

Private Sub Workbook_Open()
    If Not SheetExist("MyNewSheet") Then
        Combine
        Format
    End If
End Sub

Function SheetExist(sheetname As String) As Boolean
    SheetExist = True ' replace this with code from link below
End Function

Use the answers here: Excel VBA If WorkSheet("wsName") Exists for examples of functions that determine whether the sheet exists.

2
votes

Yea, the problem is "End Sub" should be "Exit Sub" You can also use the solution above/below.

Your fixed code would be:

Private Sub Workbook_Open()

If SheetExists("MyNewSheet") Then
    Exit Sub
Else
    Combine
    Format
End If

End Sub

Also:

Public Function SheetExists(ByVal WorksheetName As String) As Boolean 

On Error Resume Next
WorksheetExists = (Sheets(WorksheetName).Name <> "")
On Error GoTo 0

End Function