I do logging a lot. I prefer to use the On Load event and the On Close events. I also pass stuff like action ("Opened", "Closed", etc.)
FWIW: I also do thew same for reports.
Basically yu will need to have code do the exact steps you would do manually.
Here is an example updating reports that can be updated for forms.
Dim rpt As Report, mde As Module, obj As Object
Dim strCode As String, strReport As String, strEnd As String
Dim intLineNumber As Integer, strDeclaration As String
Dim strTarget As String, lngStartLine As Long, lngStartColumn As Long, lngEndLine As Long, lngEndColumn As Long
strTarget = "Private Sub Report_Open(Cancel As Integer)"
strCode = "ReportOpen (Me)"
strEnd = "End Sub"
For Each obj In CurrentProject.AllReports
strReport = obj.Name
If Left(strReport, 1) = "s" Then GoTo Skip_Report ' ignore sub reports
DoCmd.OpenReport strReport, acViewDesign
Set rpt = Reports(strReport)
Set mde = rpt.Module
With mde
' note - the find method Uses ByRef to return the positions for start and end so we need to reset them to 1
lngStartLine = 1: lngStartColumn = 1: lngEndLine = 1: lngEndColumn = 1
If .Find(strCode, lngStartLine, lngStartColumn, lngEndLine, lngEndColumn) Then ' the code doesn't already exists
DoCmd.Close acReport, strReport, acSaveNo
GoTo Skip_Report
End If
If .Find(strTarget, lngStartLine, lngStartColumn, lngEndLine, lngEndColumn) Then ' see if there is an Open Event
.InsertLines lngEndLine + 1, strCode
Else ' if not then insert it after the last procedure
If .Find("End Sub", lngStartLine, lngStartColumn, lngEndLine, lngEndColumn) Then
.InsertLines lngEndLine + 1, ""
.InsertLines lngEndLine + 2, strTarget
.InsertLines lngEndLine + 3, strCode
.InsertLines lngEndLine + 4, strEnd
Else ' or after the initial declarations
.InsertLines lngEndLine + 3, ""
.InsertLines lngEndLine + 4, strTarget
.InsertLines lngEndLine + 5, strCode
.InsertLines lngEndLine + 6, strEnd
End If
End If
DoCmd.Close acReport, strReport, acSaveYes
End With
Skip_Report:
Next
References:
https://msdn.microsoft.com/en-us/lib...or=-2147217396
https://msdn.microsoft.com/en-us/library/ff195471.aspx