+ Reply to Thread
Results 1 to 2 of 2

Excel 2007 : How to create a loop that deletes worksheets

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    12-03-2009
    Location
    California
    MS-Off Ver
    Excel 2010
    Posts
    184

    How to create a loop that deletes worksheets

    I run a macro that deletes worksheets. I have a repeating script that changes the name of the worksheet. The worksheet names are PDGroup1 PDGroup2, PDGroup3....etc, etc. How do I loop thru the same script but having it change the number at the end of PDGroup. Currently I have multiple scripts with the different PDGroup names.

    Here is what I am currently using, but multiple times

    Sub Delete_PDGroup()
        Dim sh As Worksheet
    
    Application.DisplayAlerts = False
    
        On Error Resume Next
        Set sh = ActiveWorkbook.Sheets("PDGroup1")
        If Err.Number <> 0 Then
            'MsgBox "The sheet doesn't exist"
            Err.clear
            On Error GoTo 0
        Else
            Sheets("PDGroup1").Activate
            ActiveWindow.SelectedSheets.Delete
    
    Application.DisplayAlerts = True
        End If

  2. #2
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: How to create a loop that deletes worksheets

    Maybe like this:
    Sub Delete_PDGroup()
        Dim wks          As Worksheet
    
        Application.DisplayAlerts = False
        For Each wks In ActiveWorkbook.Worksheets
            If Left(wks.Name, 7) = "PDGroup" Then wks.Delete
        Next wks
        Application.DisplayAlerts = True
    End Sub
    Entia non sunt multiplicanda sine necessitate

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1