I’m attempting to copy three sheets (two sheets are pivot tables, one is the source data for those pivots) from one workbook to a new workbook.
The code below copies the desired sheets to the new workbook and saves it (modified original):
Sub ExportFile()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
With Application
.ScreenUpdating = False
On Error GoTo ErrCatcher
' Array of sheets to copy
Sheets(Array("sourcedata", "pivot", "pivot2")).Copy
On Error GoTo 0
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
' Paste sheets
ws.[A1].PasteSpecial
' Remove external links, hyperlinks and hard-code formulas
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
' Select A1 on sheet
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Save it in the same directory as original and close
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\export.xls"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
However, when I open the new workbook, the data source in the pivot tables still point to the original workbook. My colleague explained that this is because the sheets are being copied one by one, rather in a group and suggested to copy the sheets as a range. How would I go about copying the sheets as a range or would it be easier way to change the data source to the new copied sheets?
I felt that the easiest option was to just change the data source on the pivots. Not sure if this is the cleanest syntax or if there is a shortcut, but it works for me.