OpenForm and syntax (1 Viewer)

Dumferling

Member
Local time
Today, 19:38
Joined
Apr 28, 2020
Messages
102
I have the following code to open a form:
DoCmd.OpenForm "frmCStdContractPOPIA", acNormal, , "[CVName] = " & vblType & " AND [VersionNumber] = " & vblVersion
The variables work fine but it gives a syntax error. It looks right to me. What am I doing wrong?
 

The_Doc_Man

Immoderate Moderator
Staff member
Local time
Today, 12:38
Joined
Feb 28, 2001
Messages
27,196
If either of your variables are strings, you need quoting marks. If BOTH were actually string types, it might look like this:

Code:
DoCmd.OpenForm "frmCStdContractPOPIA", acNormal, , "[CVName] = '" & vblType & "' AND [VersionNumber] = '" & vblVersion & "'"

When in doubt, assign some variable to hold the criteria as a completed string so that you can put in a breakpoint for debugging and do a manual Debug.Print (which would be visible in the Immediate window).
 

Dumferling

Member
Local time
Today, 19:38
Joined
Apr 28, 2020
Messages
102
Thank you. The problem is now a data type mismatch. My first variable is a string, the second is an integer. Does that change the syntax?
 

The_Doc_Man

Immoderate Moderator
Staff member
Local time
Today, 12:38
Joined
Feb 28, 2001
Messages
27,196
Remove the apostrophes for the case that is the integer. Literal numbers don't need quotes in this context, but strings do.

Code:
DoCmd.OpenForm "frmCStdContractPOPIA", acNormal, , "[CVName] = '" & vblType & "' AND [VersionNumber] = " & vblVersion
 

Gasman

Enthusiastic Amateur
Local time
Today, 18:38
Joined
Sep 21, 2011
Messages
14,326
Strings need to be surrounded by single quotes ' unless it contains a single quote, then triple double quotes works, I think?

Date literals with # and in mm/dd/yyyy or yyyy-mm-dd format

Numbers do not need anything

Also for anything other than one item of criteria, I tend to put the the criteria into a string variable and then debug.print it, until correct then also use that in the code.

Added benefit is, if you still cannot see the error, you can copy and paste back here for someone else to spot it. :)
 

Dumferling

Member
Local time
Today, 19:38
Joined
Apr 28, 2020
Messages
102
That worked, thank you. Great to have the help to sort out what I find to be very confusing.
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 13:38
Joined
Feb 19, 2002
Messages
43,308
Best practice when building complex strings in VBA is to build them into a variable so you can use debug.print to find typos and logic errors.
Code:
Dim strWhere as String
strWhere = "[CVName] = '" & vblType & "' AND [VersionNumber] = " & vblVersion
DoCmd.OpenForm "frmCStdContractPOPIA", acNormal, , strWhere
 

Users who are viewing this thread

Top Bottom