I've modified such that parameter body is two lines only. When I run the code
below everything works fine inserting the Workbook_Open event. When i step
through the remaining code it goes past the line
LineNum = .CreateEventProc("Change", "Worksheet")
and I see that
Private Sub Worksheet_Change(ByVal Target As Range)
End Sub
is inserted in the code module for the worksheet, it is also there in the
recovered workbook. VB then halts for 1-2 seconds while at the next line
LineNum = LineNum +1
before it crashes displaying the send error message dialog.
I'm running 2002 SP3.
Regards
ojv
Sub AddEvents()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim LineNum As Long
Dim body As String
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("ThisWorkbook")
Set CodeMod = VBComp.CodeModule
body = "Dim i as Integer" & vbCrLf & "i=0"
With CodeMod
LineNum = .CreateEventProc("Open", "Workbook")
LineNum = LineNum + 1
.InsertLines LineNum, body
End With
Set VBComp = VBProj.VBComponents(Worksheets(1).codeName)
Set CodeMod = VBComp.CodeModule
With CodeMod
LineNum = .CreateEventProc("Change", "Worksheet")
LineNum = LineNum + 1
.InsertLines LineNum, body
End With
End Sub
Hi ojv.
I believe you had to insert one instructions in one line. Try:
Sub AddEvents()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim LineNum As Long
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("ThisWorkbook")
Set CodeMod = VBComp.CodeModule
With CodeMod
LineNum = .CreateEventProc("Open", "Workbook")
LineNum = LineNum + 1
.InsertLines LineNum, "Dim i as Integer"
LineNum = LineNum + 1
.InsertLines LineNum, "i=0"
End With
End Sub
Regards
Eliano