Hi Anonymous!
This is how I would add a new worksheet and attach the "Calulate" event handler (the example shows a message box each time the calculate event is triggered):
Private Sub NewSheet_Click()
Dim oXl As Application: Set oXl = Application
oXl.EnableEvents = False
oXl.DisplayAlerts = False
oXl.ScreenUpdating = False
oXl.VBE.MainWindow.Visible = False
Dim oWs As Worksheet
Dim oVBproj As VBIDE.VBProject
Dim oVBcomp As VBIDE.VBComponent
Dim oVBmod As VBIDE.CodeModule '
Dim lLine As Single
Const QUOTE As String = """"
Set oWs = ThisWorkbook.Sheets.Add
Set oVBproj = ThisWorkbook.VBProject
Set oVBcomp = oVBproj.VBComponents(oWs.CodeName)
Set oVBmod = oVBcomp.CodeModule
With oVBmod
lLine = .CreateEventProc("Calculate", "Worksheet") + 1
.InsertLines lLine, " MsgBox " & QUOTE & "Sheet was calculated" & QUOTE
End With
oXl.EnableEvents = True
oXl.DisplayAlerts = True
End Sub
For this to work, a couple of things has to be set in Excel:
- In Excel, under Tools->Macro->Security select the tab "Trusted Sources" and check the checkbox that says "Trust access to Visual Basic Project"
- In the VBE (Visual Basic Editor), under Tools->References set a reference to "Microsoft Visual Basic for Applications Extensibility" (VBE6EXT.OLB)
The first is to allow our macro to modify objects in the visual basic project, whilst the second enable us to use the VBProject, VBComponent and CodeModule objects. You are able to to check if access to the Visual Basic Project exits at run time using code something similar to this:
Public Function gotAccessToVBE() As Boolean
Dim objVBEProj As VBIDE.VBProject
err.Clear
On Error Resume Next
Set objVBEProj = ActiveWorkbook.VBProject
If err <> 0 Then
err.Clear
On Error GoTo 0
Exit Function
End If
On Error GoTo 0
gotAccessToVBE = True
End Function
For further reading I suggest "Programming the VBA Editor" over at Pearson's.
Good luck with this
Nick:
Are there any tags I can use to enclose vb code in this forum? I would like to se the code propperly highlighted like in the VBE..