Sub AddSheetWithEventCode()
'For this procedure to work, you must add a reference to
'Microsoft Visual Basic for Applications Extensibility
'Declare variables
Dim ws As Worksheet
Dim cm As VBIDE.CodeModule
Dim x As Long
'Create a new worksheet in the active workbook
Set ws = ActiveWorkbook.Worksheets.Add
'Set a reference to the code module of the new sheet
Set cm = ws.Parent.VBProject.VBComponents(ws.Name).CodeModule
'Creat a new event procedure
x = cm.CreateEventProc("Activate", "Worksheet")
'Write code into the procedure
cm.InsertLines x + 1, "MsgBox ""Hi there!"""
cm.InsertLines x + 2, "MsgBox ""Hi again!"""
cm.InsertLines x + 3, "MsgBox ""Hi three!"""
'Release variables
Set cm = Nothing
Set ws = Nothing
End Sub
Bookmarks