Macro to copy a workbook and delete a specific worksheet

  • Thread starter Thread starter dgd1212
  • Start date Start date
D

dgd1212

How would one write a macro that makes a copy of a workbook and places it in
MyDocuments Folder? The macro also needs to delete one worksheet.
Thanks
 
This example make a copy of the activeworkbook (that workbook must be saved ones)
and delete a sheet named "Sheet1"


Sub Copy_Workbook_And_Delete_Sheet()
'Working in 2000-2007
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String

Set wb1 = ActiveWorkbook

With Application
.ScreenUpdating = False
.EnableEvents = False
End With

'If you want to change the file name then change only TempFileName
TempFilePath = Application.DefaultFilePath & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))

wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)

With wb2
'There is no error check if the sheet exist or if it is the only sheet in the workbook
Application.DisplayAlerts = False
.Sheets("Sheet1").Delete
Application.DisplayAlerts = False
.Close SaveChanges:=True
End With

With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
 
Typo
With wb2
'There is no error check if the sheet exist or if it is the only sheet in the workbook
Application.DisplayAlerts = False
.Sheets("Sheet1").Delete
Application.DisplayAlerts = False
.Close SaveChanges:=True
End With

The second DisplayAlerts line must be True instead of False
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top