Tried cobbling together some VBA to accomplish a fairly simple task. Loop through a folder of .xlsx files, open each one, remove all sheets except one with a consistent name in all of the workbooks, save the workbook with the same name.
Here is the code, but keeps throwing an error on
Public Sub RemoveSheetsLoopThroughFiles()
Dim targetWorkbook As Workbook
Dim ws As Worksheet
Dim filePath As String
Dim folderPath As String
Dim folderWildcard As String
folderPath = "[folder]\"
folderWildcard = "*.xlsx"
' Get the file path concat folder and wildcards
filePath = Dir(folderPath & folderWildcard)
Do While Len(filePath) > 0
' Open the workbook and set reference
Set targetWorkbook = Workbooks.Open(Filename:=filePath)
'Set targetWorkbook = Workbooks.Open(folderPath & folderWildcard)
For Each ws In targetWorkbook ERROR HIGHLIGHT OCCURRING HERE
Application.DisplayAlerts = False
If ws.Name <> "[sheet name to keep]" Then
ws.Delete
End If
Next ws
'Application.DisplayAlerts = True
'Debug.Print filePath
filePath = Dir
targetWorkbook.Close True
'Set targetWorkbook = Nothing
Loop
MsgBox ("all sheets removed")
End Sub