【问题标题】:Use variable to SELECT records in a recordset使用变量选择记录集中的记录
【发布时间】:2016-05-25 15:28:44
【问题描述】:

我正在尝试使用来自 ComboBox 选择结果的字符串变量从 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

【问题讨论】:

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


    【解决方案1】:

    如果是字符串,请将条件用引号括起来。即

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

    【讨论】:

      【解决方案2】:

      您可以按照 Wayne 的建议将变量的值而不是其名称连接到 SQL 语句文本中:

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-21
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2010-10-08
        • 1970-01-01
        相关资源
        最近更新 更多