Forum Discussion

Queenie Lai's avatar
Queenie Lai
Copper Contributor
Apr 20, 2020
Solved

Exit Sub not working - VBA

I am looking to loop through the names of all sheets. If the name"Apr2020" exists then Exit Sub. If it doesn't exist then copy the last sheet after the last tab. The code below does not work and cou...
  • JKPieterse's avatar
    JKPieterse
    Apr 21, 2020

    Queenie Lai I am wondering whether the loop is correct. You are looping through the name collection of the workbook object. I *think* you intended to loop through the worksheet collection:

    Sub copy()
        Dim tabname As Worksheet
        Application.ScreenUpdating = False
        Set closedBook = Workbooks.Open("C:\file123.xlsx")
        For Each tabname In closedBook.Worksheets
            If tabname.Name = "Apr2020" Then
                Exit Sub
            End If
        Next
        closedBook.Sheets(Sheets.Count).copy After:=closedBook.Sheets(Sheets.Count)
        closedBook.Close SaveChanges:=True
        Application.ScreenUpdating = True
    End Sub

Resources