Question

I am using vba code in onchange event of a combo field. the code is as below

Dim db As Database
Dim rs As DAO.Recordset
Dim qrystr As String
Dim cond As String
Dim qrystr_CID As String

'cond = [Forms]![PharmDrug].[Commercial drugs subform2].Form.DrugCompanyName & vbNullString
cond = Me.DrugCompany & vbNullString

'MsgBox cond

Set db = CurrentDb

If cond = vbNullString Then
  ' do nothing
Else
  qrystr = "SELECT DrugCompanyID FROM [Drug Company] WHERE Name ='" & cond & "';"



Set rs = db.openrecordset(qrystr)


qrystr_CID = rs!DrugCompanyID



Me.DrugCompanyID = qrystr_CID

rs.Close
Set rs = Nothing
End If

this works fine but it gives error 3075 syntax error (missing operator) in query expression 'Name= 'Dr. Redy's lab.';'

that's if the value in name field contain special characters like apostrophe etc. How can I get rid of this error ?

Please help me to solve this issue.

Was it helpful?

Solution

Use a QueryDef for a parameter query.

Dim qdf As DAO.QueryDef
qrystr = "PARAMETERS which_name TEXT(255);" & vbCrLf & _
    "SELECT DrugCompanyID FROM [Drug Company] WHERE [Name] = [which_name];"
Set qdf = db.CreateQueryDef(vbNullString, qrystr)
qdf.Parameters("which_name") = cond
Set rs = qdf.OpenRecordset

You needn't include quotes around the parameter in the SELECT statement, nor be concerned by any quotes contained within the text you supply for the parameter value. The db engine expects to receive text and will treat it as such.

I also used square brackets around [Name] because it's a reserved word. That doesn't seem to have been a problem in this case; I bracket such names routinely as a precaution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top