PDA

View Full Version : [SOLVED:] Add line of code to on open event for ALL forms



Movian
02-28-2017, 07:58 AM
I have been asked to generate some statistics on form usage and have a sub that updates a table to record whenever a form is opened....

Other than manually going to every form in the system I am hoping there is an easier method to add the line


AddFormStatistics me.name

to the on open event of every form in the system.....

HiTechCoach
02-28-2017, 09:16 PM
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/library/aa223124%28v=office.11%29.aspx?f=255&MSPPError=-2147217396

https://msdn.microsoft.com/en-us/library/ff195471.aspx

Movian
03-28-2017, 06:54 AM
Cheers, I will look at adapting this to what is needed.

Any reason you use on load over on open ?