Search code examples
sqlvbadaosql-like

Syntax for DAO 'Like' Select Query


I'm sorry for bothering you all for what is probably a really simple problem. I use DAO Select queries fairly frequently but have never needed to filter using 'Like' based on a form field.

The attached code, which should filter based on a combobox (comboRes), throws up a

Syntax error (missing operator) in query expression error.

I'm guessing the error lies in the Like '*' " & strRes & " '*' but I've tried lots of combinations with no joy.

Could someone please straighten out my syntax/code?

Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb

Dim strRes As String
strRes = Me.comboRes

Set qdf = db.QueryDefs("qryInst")

strSQL = "SELECT tblInst.*, tblInst.ResList " & _
        "FROM tblInst " & _
        "WHERE (((tblInst.ResList) Like '*' " & strRes & " '*'t ));"

qdf.SQL = strSQL

DoCmd.OpenQuery "qryInst"

qdf.Close
db.Close
Set qdf = Nothing
Set db = Nothing

Solution

  • You need to concatenate the string variable to the LIKE clause,

    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim strSQL As String
    Set db = CurrentDb
    
    Dim strRes As String
    strRes = Me.comboRes
    
    Set qdf = db.QueryDefs("qryInst")
    
    strSQL = "SELECT tblInst.*, tblInst.ResList " & _
             "FROM tblInst " & _
             "WHERE tblInst.ResList Like '*" & strRes & "*';"
    
    qdf.SQL = strSQL
    
    DoCmd.OpenQuery "qryInst"
    
    qdf.Close
    db.Close
    Set qdf = Nothing
    Set db = Nothing
    

    So if your strRes is Paul, your SQL will translate to.

    SELECT tblInst.*, tblInst.ResList FROM tblInst WHERE tblInst.ResList Like '*Paul*';"