Copy a worksheet without copying the code

After copying the sheet, you can reference it by name and then delete all of the lines from the code module:

Sheets("Example").Copy After:=Sheets("Sheet3")

' Get the code/object name of the new sheet...
Dim strObjectName As String
strObjectName = ActiveSheet.CodeName

' Remove all lines from its code module...
With ThisWorkbook.VBProject.VBComponents(strObjectName).CodeModule
    .DeleteLines 1, .CountOfLines
End With

To work with project components, you'll need to ensure that the "Trust access to the VBA project object model" option is enabled in Excel's macro settings.


Create an empty worksheet and copy the contents of the original sheet over.

Sub Copy_Sheet_Without_Code(original_sheet As String, copied_sheet As String)
    ' Creates a copy of original_sheet without any VBA code associated with it
    ' The copy is named copied_sheet
    Sheets(original_sheet).Cells.Copy
    Sheets.Add.Name = copied_sheet
    Sheets(copied_sheet).Cells.PasteSpecial Paste:=xlPasteAll
End Sub

Not exactly what the OP wanted, but you can also remove the worksheet macros by copying the worksheet to a new workbook, and then saving that workbook using the following code (which ultimately saves the workbook as .xlsx and strips the code away) ...

ActiveWorkbook.SaveAs fileName:="yourfile.xlsx", fileFormat:=51

This has the benefit of persisting all the data and formatting (eg column widths), and doesn't require VBA object model permissions.

Of course, once saved, you could then reopen the saved workbook and move the sheet back into the original workbook, now without the code!

Tags:

Excel

Vba