使用变量来记录记录集中的记录

时间:2016-05-25 15:28:44

标签: ms-access access-vba ms-access-2016

我正在尝试使用ComboBox选择结果中的String变量从Access表中选择记录。我已确认变量(zBEN)在选中时包含正确的数据。如果我在语句的WHERE部分手动输入数据,它就能完美运行。如果我使用zBEN它会崩溃 - 如果我不使用单引号我会收到错误,如果我使用引号,我会得到一个空记录集。错误是3061,参数太少。预期1.此错误通常是数据类型不匹配或字段名称不正确。

Private Sub cmdDisplayMembers_Click()
'this displays a record in the dataset - from button click
Dim dbsContacts As DAO.Database
Dim rcdContacts As DAO.Recordset
Dim conArray As Variant              'this is the record array
Dim intArraySize As Integer         'array size
Dim iCtr As Integer                 'counter
Dim zBEN As Variant
Dim zName, strSQL  As String
zBEN = Me.cbxMembersList

Set dbsContacts = CurrentDb
'this statement works: (and has the combobox value manually entered
strSQL = "SELECT * FROM tblMember_Contact where id_members = '201208FEAR' ORDER BY id_members"
'this statement gives an error 3061, 1:
'strSQL = "SELECT * FROM tblMember_Contact where id_members = zBEN ORDER BY id_members"
'this statement gives an empty record set
'strSQL = "SELECT * FROM tblMember_Contact where id_members = 'zBEN' ORDER BY id_members"

Set rcdContacts = dbsContacts.OpenRecordset(strSQL)
If Not rcdContacts.EOF Then
    rcdContacts.MoveFirst              'start the counter at Row #1
    intArraySize = rcdContacts.RecordCount
    iCtr = 1
    ReDim conArray(10)

    Do Until rcdContacts.EOF
        conArray(iCtr) = rcdContacts.Fields("member_info")
        Debug.Print "Item: "; iCtr & " " & conArray(iCtr)

        iCtr = iCtr + 1
        rcdContacts.MoveNext
    Loop
MsgBox ("Error no records")
End If

If IsObject(rcdContacts) Then Set rcdContacts = Nothing
txtCon1 = conArray(1)
txtCon2 = conArray(2)
MsgBox (zBEN)
End Sub

2 个答案:

答案 0 :(得分:1)

如果标准是字符串,则将标准括在引号中。即。

strSQL = "SELECT * FROM tblMember_Contact where id_members = '" & zBEN & "' ORDER BY id_members"

答案 1 :(得分:1)

您可以将变量的值而不是其名称连接到SQL语句文本中,如Wayne已经建议的那样:

strSQL = "SELECT * FROM tblMember_Contact where id_members = '" & zBEN & "' ORDER BY id_members"

但是如果切换到参数查询方法,则无需担心引号:

strSQL = "SELECT * FROM tblMember_Contact where id_members = [which_id] ORDER BY id_members"
Dim qdf As DAO.QueryDef
Set qdf = dbsContacts.CreateQueryDef(vbNullString, strSQL )
qdf.Parameters("which_id").Value = Me!cbxMembersList.Value
Set rcdContacts = qdf.OpenRecordset()