Excel VBA – Copy worksheets and save as a new file

If you copy data from one sheet to another the formula refer back to the original sheet. Doing a ‘past special’ and copying only the data can do the trick. But if you need to do such operations for a large number of sheets a VBA macro can be handy:

Sub CopyPasteSave()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet

If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub

With Application
.ScreenUpdating = False

' Copy specific sheets
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
On Error GoTo 0

' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.[A1].PasteSpecial Paste:=xlValues
Application.CutCopyMode = False
Cells(1, 1).Select
Next ws
Cells(1, 1).Select

' Remove named ranges
For Each nm In ActiveWorkbook.Names
Next nm

' Input box to name new file
'NewName = InputBox("Please Specify the name of your new workbook", "New Copy")

' Save it with the NewName and in the same directory as original
NewName = ThisWorkbook.Name & "_out"
'ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "" & NewName & ".xls"
ActiveWorkbook.Close SaveChanges:=True

.ScreenUpdating = True
End With
Exit Sub

MsgBox "Specified sheets do not exist within this workbook"
End Sub

This code will ask for the new file name before it closes. You can tweak the code to suit your requirement.


2 thoughts on “Excel VBA – Copy worksheets and save as a new file

  1. Hi!

    First off, I want to thank you for this Macro, it has helped me tremendously! I know it is getting dated, but I will try to ask here as I cannot find the answer elsewhere.. Hopefully you will get this post!

    When exporting the sheets, I want to keep my Print Area settings, do you have a tip for how this could be done?

    A tip for anyone who wants to use this and has a file with alot of data:
    Add .Calculation = xlCalculationManual at the beginning of the macro and add .Calculation = xlCalculationAutomatic at the end, this way the process is much quicker!

    Thank you again!

Leave a Reply to Carl Cancel reply

Your email address will not be published. Required fields are marked *