我有 2 个列表框,定义了 2 个需要通过 SQL 语句传递给 OpenRecordSet 的变量。
传送带_ID是访问表名
Width是表Conveyor_ID中的字段名称
行宽是字段宽度中的字符串值
Dim db As DAO.Database
Dim rs As DAO.Recordset
Const DbLoc As String = "DB location info"
Dim Conveyor_ID As String ' Conveyor ID Table
Dim Width_Row As String ' Width row, string values such as 12" or 12in
Set rs = db.OpenRecordset("SELECT * FROM " & [Conveyor_ID] & " Where Width = " & [Width_Row])
根据为 Width_row 选择的值,我将收到两个不同的错误。
如果选择“14in”,“查询表达式 'Width = 14in' 中没有 () 的 In 运算符”的错误
如果选择“14”,错误“查询表达式‘Width = 12’中的字符串存在语法错误”。
我相信我不理解向传递到 Openrecordset 方法的 SQL 字符串添加变量的语法。
问题是您传递的字符串不带任何引号,并将其与 SQL 连接起来。这会导致无效的 SQL。
这意味着您的最终字符串可能类似于:
SELECT * FROM someTable Where Width = 12in
这不是有效的 SQL。 SQL 中的字符串需要用单引号或双引号引起来。
有多种方法可以解决这个问题。正确的方法是使用参数。
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qd As DAO.QueryDef
Const DbLoc As String = "DB location info"
Dim Conveyor_ID As String ' Conveyor ID Table
Dim Width_Row As String ' Width row, string values such as 12" or 12in
Set db = CurrentDb 'You were missing this in your sample
Set qd = db.CreateQueryDef("", "SELECT * FROM " & [Conveyor_ID] & " Where Width = @theWidth")
qd.Parameters("@theWidth") = [Width_Row]
Set rs = qd.OpenRecordset
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)