Perhaps if you explained the "good reason why [you] need to do it this way"
we could suggest an alternative.
You can, of course, add code to modules programmatically. Here's some
untested air-code that will open every report in the application. If there
is a "Report_Open" sub already, the code will add a line "Call MyFunction()"
at the top of that sub. If there isn't a "Report_Open" sub, it will create
it, with the one line of code "Call MyFunction()" in that sub.
Sub AddCode()
Dim dbCurr As DAO.Database
Dim rsCurr As DAO.Recordset
Dim rptCurr As Report
Dim mdlCurr As Module
Dim lngSLine As Long, lngSCol As Long
Dim lngELine As Long, lngECol As Long
Dim lngReturn As Long
Dim strReportName As String
Dim strSQL As String
strSQL = "SELECT [Name] FROM MSysObjects " & _
"WHERE [Type] = -32764 ORDER BY [Name]"
Set dbCurr = CurrentDb()
Set rsCurr = dbCurr.OpenRecordset(strSQL)
Do Until rsCurr.EOF
strReportName = rsCurr!Name
Debug.Print "Working on report " & strReportName
DoCmd.OpenReport strReportName, acViewDesign
Set rptCurr = Reports(strReportName)
Set mdlCurr = rptCurr.Module
' Search for string "Private Sub Report_Open"
If mdlCurr.Find("Private Sub Report_Open", _
lngSLine, lngSCol, lngELine, lngECol) Then
Debug.Print "Code added after line " & lngSLine
mdlCurr.InsertLines lngSLine + 1, "Call MyFunction()" & vbCrLf
Else
Debug.Print "Module not found: it was created."
lngReturn = mdlCurr.CreateEventProc("Open", "Report")
mdlCurr.InsertLines lngReturn + 1, "Call MyFunction()"
End If
DoCmd.Close acReport, strReportName, acSaveYes
rsCurr.MoveNext
Loop
rsCurr.Close
Set rsCurr = Nothing
Set dbCurr = Nothing
End Sub
--
Doug Steele, Microsoft Access MVP
(no private e-mails, please)
Thanks Doug,
Yes, I was hoping to avoid pasting a call to a function in the OnOpen
event of all 110 reports. I guess I am really looking for some global
code that will change the behaviour of all the reports in the database.
OK - here's a sub-question: is there any way of adding the Function
call to each report's OnOpen event when the database starts up e.g For
each report, insert one line of code at the head of each report's
OnOpen event bearing in mind that most of the reports already have some
code in their OnOpen events. By the way, this is not just laziness on
my part - there is a good reason why I need to do it this way.
Thanks again.