Damon Ostrander
MrExcel MVP
- Joined
- Feb 17, 2002
- Messages
- 4,239
I was recently asked for code to copy a worksheet code module to a different worksheet. I'm posting the code here in case anybody else is interested.
Note that this example code creates a new sheet, and copies the code module from Sheet1. There is no way to simply copy the entire code module in one step, so this code copies the code line by line in a For loop, but it appears to run very fast.
Note that you do need to set a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 library via Tools > References in the Visual Basic Editor.
Keep Excelling.
Code:
Sub CodeCopy()
'Macro to create a new sheet and copy the macro module
'from sheet1 to it. Must install Microsoft Visual Basic
'for Applications Extensibility library from Tools > References.
Dim i As Integer
Dim NewSh As Worksheet
Dim SrcCmod As VBIDE.CodeModule
Dim DstCmod As VBIDE.CodeModule
Set NewSh = Worksheets.Add(after:=Worksheets(Worksheets.Count))
Set SrcCmod = ActiveWorkbook.VBProject.VBComponents("Sheet1").CodeModule
Set DstCmod = ActiveWorkbook.VBProject.VBComponents(NewSh.Name).CodeModule
For i = 1 To SrcCmod.CountOfLines
DstCmod.InsertLines i, SrcCmod.Lines(i, 1)
Next i
End Sub
Note that this example code creates a new sheet, and copies the code module from Sheet1. There is no way to simply copy the entire code module in one step, so this code copies the code line by line in a For loop, but it appears to run very fast.
Note that you do need to set a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 library via Tools > References in the Visual Basic Editor.
Keep Excelling.