2
votes

Using Access 2007. I'm trying to write a VBA function that will construct a query from the table name, fields, and values that I pass as parameters. I keep getting a "Run-time error '3464': Data type mismatch in criteria expression."

Here's the code:

Function getPrimaryFromForeign(db As Database, table As String, field As String, _
                            value As Long, _
                            field2 As String, value2 As Long) As Long

Dim sStr As String
Dim istr As String
Dim rs As Recordset



sStr = "select * from " & table & " where " _
        & field & "='" & value & "' and " & field2 & "='" & value2 & "'"
    istr = "insert into " & table & "(" & _
    field & "," & field2 & ") values ('" & value & "','" & value2 & "')"



Set rs = db.OpenRecordset(sStr)

If rs.RecordCount < 1 Then
    db.Execute (istr), dbFailOnError
    Set rs = db.OpenRecordset(sStr)
End If
getPrimaryFromForeign = rs("id")

End Function

The error occurs at the line: Set rs = db.OpenRecordset(sStr)

I think it has something to do with the variable types of Value and Value2. But I've checked them using typename(), and they're both Long when OpenRecordSet() is called. The query is on a table where both of those fields are of type Number. So why is there a type mismatch?

2

2 Answers

1
votes

I haven't used Access in a long time, but I think that the problem is because you're enclosing Value and Value2 in single quotes in your SQL statement, and not enclosing the fields in the WHERE clause in brackets.

Try it like this:

sStr = "select * from " & table & " where [" _
            & field & "] = " & value & " and [" & field2 & "] = " & value2
istr = "insert into " & table & "([" & _
            field & "], [" & field2 & "]) values (" & value & "," & value2 & ")"
1
votes

This can occur if you have both DAO and an ADO in you reference library.
In this case declaration order in both your Dim statements and in the references window matters.

1) "You must reference and use both DAO and ADO Recordset objects, dimension the objects explicitly as follows:

Dim adoRS As ADODB.Recordset
Dim daoRS As DAO.Recordset"

2) "Make sure that the reference for the DAO object library has a higher priority in the References dialog box, or clear the reference to Microsoft ActiveX Data Objects."

see Here: https://support.microsoft.com/en-us/help/181542/you-receive-a-type-mismatch-error-when-you-run-the-openrecordset-metho