Tuan Kriel
New Member
- Joined
- Sep 28, 2017
- Messages
- 7
Require code to copy any of the selected worksheets and VBA modules to a new workbook in Excel
Thanks Trevor, this would not be viable as many different users will use the workbook as a template who would then like to select some worksheets applicable to them and save it in a different location every time.It maybe easier to save the workbook as a copy and delete the sheets you don't need that way the VBA Modules are included without coding to copy the modules.
It maybe easier to save the workbook as a copy and delete the sheets you don't need that way the VBA Modules are included without coding to copy the modules.
Public Sub Save_Selected_Sheets_In_New_Macro_Workbook()
Dim sheetsList As String
Dim sh As Object
Dim saveAsFile As Variant
With ThisWorkbook
sheetsList = "|"
For Each sh In ActiveWindow.SelectedSheets
sheetsList = sheetsList & sh.Name & "|"
Next
saveAsFile = Application.GetSaveAsFilename(InitialFileName:="", FileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
If saveAsFile <> False Then
.SaveAs saveAsFile, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = False
For Each sh In .Sheets
If InStr(sheetsList, "|" & sh.Name & "|") = 0 Then
sh.Delete
End If
Next
Application.DisplayAlerts = True
.Save
End If
End With
End Sub
Thanks John, I've managed to solve it on my own see here below:Going with Trevor's suggestion - otherwise you have to change Macro settings to 'Trust access to the VBA project object model' in order to copy VBA modules - this macro prompts for the save file name and location and the newly saved workbook becomes the active workbook.
VBA Code:Public Sub Save_Selected_Sheets_In_New_Macro_Workbook() Dim sheetsList As String Dim sh As Object Dim saveAsFile As Variant With ThisWorkbook sheetsList = "|" For Each sh In ActiveWindow.SelectedSheets sheetsList = sheetsList & sh.Name & "|" Next saveAsFile = Application.GetSaveAsFilename(InitialFileName:="", FileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm") If saveAsFile <> False Then .SaveAs saveAsFile, FileFormat:=xlOpenXMLWorkbookMacroEnabled Application.DisplayAlerts = False For Each sh In .Sheets If InStr(sheetsList, "|" & sh.Name & "|") = 0 Then sh.Delete End If Next Application.DisplayAlerts = True .Save End If End With End Sub