How to make TempVars work with OpenRecordset

Recently Maarten a blog reader asks:

TempVars (introduced with Access 2007) are great! But I have some problems in using them.

I created a query with a TempVar as criteria. When I run the query it shows the correct data. But when I open the query in VBA using OpenRecordset, I get the message: “Run-time error 3061: Too few parameters. Expected 1.”

This is the expected behavior. TempVars are defined in the scope of the Access Application object. When you use the CurrentDB.OpenRecordset method, the resulting recordset is defined in the scope of the ACE database engine (DAO).

Here is a workaround. Create and form based on the query and assign your recordset to it. Something like this…

DoCmd.OpenForm "FormName", WindowMode:=acHidden
Set rs = Forms("FormName").Recordset

... Do stuff

DoCmd.Close acForm, "FormName"

Enjoy!

Office Blogs Comments

Comments: (4) Collapse

  • It might be easier to use a small function that wraps the TempVars collection: Public Function GetTempVar(strTempVar As String) GetTempVar = TempVars(strTempVar)

    End Function SELECT * FROM tblTest WHERE SampleField = GetTempVar(MyArgument)

  • I'm not sure I follow your point about the Nz (and similar) methods. Certainly this code works while you seem to suggest it would not:

    (in a VBA module:)

    Dim rs As DAO.Recordset

    Set rs = CurrentDb.OpenRecordset("select * from Customers where Nz(ID)=1") -Tom.

  • You are absolutely right Tom. I forgot that we plumbed Nz into ACE. I removed the Nz() reference from the post.

  • I write about using tempvars in this article on how to speed up a database

    www.vb123.com.au/.../needforspeed.htm

Comments

Comments: (loading) Collapse