简体   繁体   中英

Access combo box and subform

I've got a subform on a form with a combo box. I want to select a standard number from the box and have the subform only show those records. I've run into a syntax error (missing operator) in query expression. Can someone help?

Private Sub cbo_st_no_AfterUpdate()

    Dim standardNo As String

    standardNo = "Select * from StandardsList where ([st_no] = " & Me.cbo_st_no & ")"

    Me.WhoDoneItSubformy.Form.RecordSource = standardNo
    Me.WhoDoneItSubformy.Form.Requery

End Sub

The error you get syntax error (missing operator) in query expression points out that Me.cbo_st_no doesn't return a value.

That could happen if no entry is selected in the combobox yet.

So in case no entry is selected yet in the combo box, you should think about if all or no record should be displayed in the subform.

This is a full example assuming st_no is a number field:

Private Sub cbo_st_no_AfterUpdate()
    Dim standardNo As String

    If Len(Nz(Me.cbo_st_no)) = 0 Then
        'To show nothing:
        standardNo = "Select * From StandardsList Where False"
        'To show all:
        standardNo = "Select * From StandardsList"
    Else
        standardNo = "Select * From StandardsList Where [st_no] = " & Me.cbo_st_no
    End If

    Me.WhoDoneItSubformy.Form.RecordSource = standardNo
    Me.WhoDoneItSubformy.Form.Requery
End Sub

More info:

If the field st_no is a text field then you have to wrap the value in ' :

"Select * From StandardsList Where [st_no] = '" & Me.cbo_st_no & "'"

The answer by Unhandled Exception is good, but the code can be simplified significantly, both yours and the solution. This is what I would do:

Private Sub cbo_st_no_AfterUpdate()
    Me.WhoDoneItSubformy.RecordSource = "SELECT * from StandardsList WHERE st_no=" & Nz(Me.cbo_st_no,0)
    Me.WhoDoneItSubformy.Requery
End Sub

If zero is an existing value for st_no use -1 or any other value guaranteed not to match an existing record. If you prefer that a null value shows all records instead of none use

Nz(Me.cbo_st_no,"st_no")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM