1

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.

Fionnuala
  • 90,370
  • 7
  • 114
  • 152
Gopipuli
  • 393
  • 1
  • 12
  • 37
  • 3
    see http://stackoverflow.com/q/199889/603855 and consider using parameterized queries instead of replacing "'" (single quote) with "''" (two single quotes). – Ekkehard.Horner Nov 05 '12 at 09:42
  • 1
    There is only one small problem with parameters and that is for data longer than 255 characters (memo data type). However, it won't be a problem in this case. – Fionnuala Nov 05 '12 at 09:50

1 Answers1

2

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.

HansUp
  • 95,961
  • 11
  • 77
  • 135