VBA Loop to remove specific named worksheets within a folder

RyanHawkeye

New Member
Joined
Apr 9, 2015
Messages
44
Hello, I'm needing some help from you experts out there. I have a folder with multiple xlsx spreadsheets within it. I would truly love to have VBA Loop code rummage through all the folder's xlsx spreadsheets and keep worksheets named AR20, AR21, VT77, and GG65 and delete all the other worksheets. Any help will be appreciated. Thanks
 
Untested here.

VBA Code:
Option Explicit

Sub KeepSpecificSheets()
    Dim FolderPath As String
    Dim Filename As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim MasterWorkbook As Workbook
    Dim KeepSheets As Object
    Dim wsName As String
    Dim FoundSheet As Boolean
   
    Application.DisplayAlerts = False
   
    ' Set the folder path
    FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path
    If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"
   
    ' Store the master workbook
    Set MasterWorkbook = ThisWorkbook
   
    ' Define sheets to keep in a dictionary
    Set KeepSheets = CreateObject("Scripting.Dictionary")
    KeepSheets.Add "AR20", True
    KeepSheets.Add "AR21", True
    KeepSheets.Add "VT77", True
    KeepSheets.Add "GG65", True
   
    ' Loop through all xlsx files in the folder
    Filename = Dir(FolderPath & "*.xlsx")
    Do While Filename <> ""
        ' Open the workbook if it is not the master workbook
        If StrComp(FolderPath & Filename, MasterWorkbook.FullName, vbTextCompare) <> 0 Then
            Set wb = Workbooks.Open(FolderPath & Filename)
            FoundSheet = False ' Initialize flag
           
            ' Check if any sheets to keep exist
            For Each ws In wb.Worksheets
                If KeepSheets.exists(ws.Name) Then
                    FoundSheet = True
                    Exit For
                End If
            Next ws
           
            ' If no sheets match the keep list, delete the workbook
            If Not FoundSheet Then
                wb.Close SaveChanges:=False ' Close without saving changes
                Kill FolderPath & Filename ' Delete the file
            Else
                ' Loop through all worksheets in the workbook to delete non-matching sheets
                For Each ws In wb.Worksheets
                    wsName = ws.Name
                    If Not KeepSheets.exists(wsName) Then
                        ws.Visible = xlSheetVisible ' Make sheet visible if hidden
                        ws.Delete
                    End If
                Next ws
               
                ' Save the workbook with a 'Confidential' setting
                Dim SavePath As String
                SavePath = FolderPath & wb.Name & "_Confidential.xlsx"
               
                ' Add a custom document property to indicate confidentiality
                On Error Resume Next
                wb.CustomDocumentProperties.Add Name:="Confidential", _
                    LinkToContent:=False, Type:=msoPropertyTypeString, Value:="True"
                On Error GoTo 0
               
                ' Save the workbook
                wb.SaveAs Filename:=SavePath, FileFormat:=xlOpenXMLWorkbook
                wb.Close SaveChanges:=False
            End If
        End If
       
        ' Get the next file
        Filename = Dir
    Loop
   
    Application.DisplayAlerts = True
   
    MsgBox "Process Completed!", vbInformation
End Sub
Logit, this is close. I dont want the spreadsheet named with "Confidential.xlsx" at the end. I just want to keep the spreadsheet name the same. This actually double the amount of spreadsheets in the folder because it updated the current spreadsheet with the new Confidential.xslx and left the current spreadsheet without changes in the folder. If we can get "Confidential.xslx removed and just update the spreadsheet without changing the name that would be awesome. Thanks! Here is a pic of how it doubles the spreadsheets btw
1736870821426.png
 
Upvote 0

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
VBA Code:
Option Explicit

Sub KeepSpecificSheets()
    Dim FolderPath As String
    Dim Filename As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim MasterWorkbook As Workbook
    Dim KeepSheets As Object
    Dim wsName As String
    Dim FoundSheet As Boolean
  
    Application.DisplayAlerts = False
  
    ' Set the folder path
    FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path
    If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"
  
    ' Store the master workbook
    Set MasterWorkbook = ThisWorkbook
  
    ' Define sheets to keep in a dictionary
    Set KeepSheets = CreateObject("Scripting.Dictionary")
    KeepSheets.Add "AR20", True
    KeepSheets.Add "AR21", True
    KeepSheets.Add "VT77", True
    KeepSheets.Add "GG65", True
  
    ' Loop through all xlsx files in the folder
    Filename = Dir(FolderPath & "*.xlsx")
    Do While Filename <> ""
        ' Open the workbook if it is not the master workbook
        If StrComp(FolderPath & Filename, MasterWorkbook.FullName, vbTextCompare) <> 0 Then
            Set wb = Workbooks.Open(FolderPath & Filename)
            FoundSheet = False ' Initialize flag
          
            ' Check if any sheets to keep exist
            For Each ws In wb.Worksheets
                If KeepSheets.exists(ws.Name) Then
                    FoundSheet = True
                    Exit For
                End If
            Next ws
          
            ' If no sheets match the keep list, delete the workbook
            If Not FoundSheet Then
                wb.Close SaveChanges:=False ' Close without saving changes
                Kill FolderPath & Filename ' Delete the file
            Else
                ' Loop through all worksheets in the workbook to delete non-matching sheets
                For Each ws In wb.Worksheets
                    wsName = ws.Name
                    If Not KeepSheets.exists(wsName) Then
                        ws.Visible = xlSheetVisible ' Make sheet visible if hidden
                        ws.Delete
                    End If
                Next ws
              
                ' Save the workbook with a 'Confidential' setting
                Dim SavePath As String
                SavePath = FolderPath & wb.Name                                                                             '---> got rid of this                     & "_Confidential.xlsx"
              
                ' Add a custom document property to indicate confidentiality
                On Error Resume Next
                wb.CustomDocumentProperties.Add Name:="Confidential", _
                    LinkToContent:=False, Type:=msoPropertyTypeString, Value:="True"
                On Error GoTo 0
              
                ' Save the workbook
                wb.SaveAs Filename:=SavePath, FileFormat:=xlOpenXMLWorkbook
                wb.Close SaveChanges:=False
            End If
        End If
      
        ' Get the next file
        Filename = Dir
    Loop
  
    Application.DisplayAlerts = True
  
    MsgBox "Process Completed!", vbInformation
End Sub
 
Upvote 0
VBA Code:
Option Explicit

Sub KeepSpecificSheets()
    Dim FolderPath As String
    Dim Filename As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim MasterWorkbook As Workbook
    Dim KeepSheets As Object
    Dim wsName As String
    Dim FoundSheet As Boolean
 
    Application.DisplayAlerts = False
 
    ' Set the folder path
    FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path
    If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"
 
    ' Store the master workbook
    Set MasterWorkbook = ThisWorkbook
 
    ' Define sheets to keep in a dictionary
    Set KeepSheets = CreateObject("Scripting.Dictionary")
    KeepSheets.Add "AR20", True
    KeepSheets.Add "AR21", True
    KeepSheets.Add "VT77", True
    KeepSheets.Add "GG65", True
 
    ' Loop through all xlsx files in the folder
    Filename = Dir(FolderPath & "*.xlsx")
    Do While Filename <> ""
        ' Open the workbook if it is not the master workbook
        If StrComp(FolderPath & Filename, MasterWorkbook.FullName, vbTextCompare) <> 0 Then
            Set wb = Workbooks.Open(FolderPath & Filename)
            FoundSheet = False ' Initialize flag
         
            ' Check if any sheets to keep exist
            For Each ws In wb.Worksheets
                If KeepSheets.exists(ws.Name) Then
                    FoundSheet = True
                    Exit For
                End If
            Next ws
         
            ' If no sheets match the keep list, delete the workbook
            If Not FoundSheet Then
                wb.Close SaveChanges:=False ' Close without saving changes
                Kill FolderPath & Filename ' Delete the file
            Else
                ' Loop through all worksheets in the workbook to delete non-matching sheets
                For Each ws In wb.Worksheets
                    wsName = ws.Name
                    If Not KeepSheets.exists(wsName) Then
                        ws.Visible = xlSheetVisible ' Make sheet visible if hidden
                        ws.Delete
                    End If
                Next ws
             
                ' Save the workbook with a 'Confidential' setting
                Dim SavePath As String
                SavePath = FolderPath & wb.Name                                                                             '---> got rid of this                     & "_Confidential.xlsx"
             
                ' Add a custom document property to indicate confidentiality
                On Error Resume Next
                wb.CustomDocumentProperties.Add Name:="Confidential", _
                    LinkToContent:=False, Type:=msoPropertyTypeString, Value:="True"
                On Error GoTo 0
             
                ' Save the workbook
                wb.SaveAs Filename:=SavePath, FileFormat:=xlOpenXMLWorkbook
                wb.Close SaveChanges:=False
            End If
        End If
     
        ' Get the next file
        Filename = Dir
    Loop
 
    Application.DisplayAlerts = True
 
    MsgBox "Process Completed!", vbInformation
End Sub
Hi Logit, I now get a runtime error when I use this code. Run-time error '1004': Cant Access the spreadsheet.
 
Upvote 0
What line of code is highlighted? Anytime you get an error is to include the offending code line/s in your question.

Did you include the actual path in this line of code :
VBA Code:
 Set the folder path
    FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path
 
Upvote 0
What line of code is highlighted? Anytime you get an error is to include the offending code line/s in your question.

Did you include the actual path in this line of code :
VBA Code:
 Set the folder path
    FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path
Yes I used the same exact path I just double checked. It just gives that error 1004 and it gives the name of the very first spreadsheet in the folder and says it cant access it.
When I click the debug button it shows this...if this helps at all.
1736968921524.png
 
Upvote 0
What line of code is highlighted? Anytime you get an error is to include the offending code line/s in your question.

Did you include the actual path in this line of code :
VBA Code:
 Set the folder path
    FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path
I also noticed that the first spreadsheet where this error pops up now only shows the tabs needed correctly, it just never applied the Sensitivity Label of Confidential to the spreadsheet, so that looks to be the spot where the code errored out at. I showed you the "Debug" pic above.
 
Upvote 0
I'm confused when you say "I used the same exact path".

You should not be using this :

VBA Code:
FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path

Your path would be something like (but not identical to this) :

FolderPath = "C:\Users\logit\OneDrive\Desktop\MySaveFolder"

Description :
- 'C' is your hard drive. That doesn't change in this project.

- 'Users' refers to a section on your hard drive where all of your files are maintained. This also doesn't change in this project.

- 'logit' refers to the name of your computer. This needs to change to match your computer. When you startup your computer the initial welcome screen displays the name of your computer that you assigned to it initially. That is the name that replaces 'logit' in this path.

- '\OneDrive\Desktop\' also don't change in this project.

- 'MySaveFolder' is the name of the folder you create on your desktop where all the files will be copied to when running these macros. You can name the folder anything you want but make certain in the path coding you use the same name.
 
Upvote 0
I'm confused when you say "I used the same exact path".

You should not be using this :

VBA Code:
FolderPath = "C:\Your\Folder\Path\" ' Change this to your folder path

Your path would be something like (but not identical to this) :

FolderPath = "C:\Users\logit\OneDrive\Desktop\MySaveFolder"

Description :
- 'C' is your hard drive. That doesn't change in this project.

- 'Users' refers to a section on your hard drive where all of your files are maintained. This also doesn't change in this project.

- 'logit' refers to the name of your computer. This needs to change to match your computer. When you startup your computer the initial welcome screen displays the name of your computer that you assigned to it initially. That is the name that replaces 'logit' in this path.

- '\OneDrive\Desktop\' also don't change in this project.

- 'MySaveFolder' is the name of the folder you create on your desktop where all the files will be copied to when running these macros. You can name the folder anything you want but make certain in the path coding you use the same name.
I mean I am using the same path I have used prior to get to the Folder that resides in My Documents. I am not just using the generic example you provided.
 
Upvote 0
Maybe we could use the way that almost worked. Instead of ending the updated files with Confidential.xlsx, you could end it with Updated.xlsx. Then delete the other spreadsheets that dont have Updated.xlsx so there arent double the spreadsheets within the folder.
 
Upvote 0
Ok ... I'm glad we cleared that up.

Would you consider posting your workbook to a download site ? That way we can directly see what is going on and
hopefully how to correct it.
 
Upvote 0

Forum statistics

Threads
1,225,606
Messages
6,185,957
Members
453,333
Latest member
BioCoder84

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top