Question : Changing Report Recordsource Property in VBA

Using Access 2000

this is the same project I asked about making the cutsom report for..
We have a query whose SQL string is concatenated according to selections a user makes on a form.
the user can view a report or a query result for these selections.
the user has the option of saving their settings.  First they are prompted for a name (goes into a variable called newqryname).  The "on the fly" SQL statement is saved as a query with that name.
Next they are asked if they wish to save a report for that query.  If they select yes, Access should copy the "on the fly" report - that part works fine.
Next, Access needs to change the recordsource of the newly named report to match the newly named query.
I was using the same variable (newaryname) so everything would have the save name. the report would be report!newqryname, the query would be querydefs(newqryname).

I keep getting errors when I try and change the recordsource property of the new report.
If I try and change the recordsource with the Reports' module, I get an error saying I'm not allowed to do this.  If I try and reference the Reports collection, Access can't see it because it isn't open.
If I open it and then try to change the recordsource, I get an error because its open.
If I use the AllReports collection, which sees both open and closed reports, it sees the report but tells me I have a type mismatch when I try and set the recordsource to the query's name.

the latest code I've tried is:

ans2 = MsgBox("Do you want to save a report for this query?", vbYesNo, "saving current settings")
    If ans2 = 7 Then
    End If
    If ans2 = 6 Then

    DoCmd.CopyObject , newqryname, acReport, "CustomReport"  

    Set ARpts = CurrentProject.AllReports
    Set Rpt = ARpts(newqryname)
    Rpt.RecordSource = newqryname

any ideas on what might work??

Answer : Changing Report Recordsource Property in VBA

SBFurr,

The reason you were getting an error message about the data mismatch was caused by the fact that ARpts(newqryname) returns a reference to an object of type AccessObject. Probably you declared rpt as a Report-object.
Anyway, in order to change the recordsource of your new report you have to open this report in design mode first.
Then you can alter its recordsource. I made a small routine which might give you the idea about how to do it.

Sub CreateNewReport()
  Dim strNewQuery As String
 
  strNewQuery = "qryLikeM" ' name of some dynamically created and saved query
 
  ' created a copy of rptNames
  DoCmd.CopyObject , strNewQuery, acReport, "rptNames"
  ' open this new report in design-mode
  DoCmd.OpenReport strNewQuery, acViewDesign
 
  ' now you can change the recordsource
  Reports(strNewQuery).RecordSource = strNewQuery
  ' close new form without prompting
  DoCmd.Close acReport, strNewQuery, acSaveYes
 
End Sub


Mark
Random Solutions  
 
programming4us programming4us