【问题标题】:Trouble using "Like" in SQL Statement in VBA for Access 2013在 VBA for Access 2013 的 SQL 语句中使用“Like”时遇到问题
【发布时间】:2016-12-18 12:56:36
【问题描述】:

我已经阅读了数百个问题和答案,但我似乎无法让它发挥作用。我正在尝试使用此 SQL 语句来设置列表框的行源...

If searchOpt = 1 Then
    sqlStr = "SELECT tblEquipment.anumEquipID," & _
    "   tblEquipment.strPCN," & _
    "   tblEquipment.strDescription," & _
    "   tblEquipment.strOwnerDepartment," & _
    "   tblEquipment.strPrimaryID," & _
    "   tblEquipment.strSecondaryID," & _
    "   tblEquipment.strNote," & _
    "   tblEquipment.ynCapitalItem," & _
    "   tblEquipment.strLocation," & _
    "   tblContacts.strPrimaryContact," & _
    "   tblContacts.strPrimaryPhone" & _
    "   FROM tblContacts RIGHT JOIN tblEquipment ON tblContacts.anumID = tblEquipment.strPrimaryID" & _
    "   WHERE (((tblEquipment.strDescription) Like " * " & [Forms]![frmSearch]![strSearchBox] & " * "));"

使用上述方法时,我不断收到“类型不匹配”错误。我尝试更改引号并将 * 更改为 %,但我会收到“语法”错误或没有错误,但不会填充列表框。顺便说一句,此代码与一个按钮相关联,该按钮被按下以使用表单上的未绑定文本框搜索数据字段“strDescription”的文本。

非常感谢您能提供的任何帮助。谢谢

【问题讨论】:

    标签: vba ms-access sql-like


    【解决方案1】:

    * 也表示“将两个东西相乘”(例如x * y),因此当您尝试将两个字符串相乘时,格式错误的代码会给您一个类型错误(因为当然,这没有任何意义!)

    您真正想要的是最后一行封装 * 而不是在它们之间使用 * 操作的单独字符串。替换为:

    "   WHERE (((tblEquipment.strDescription) Like ""*"" & [Forms]![frmSearch]![strSearchBox] & ""*""));"
    

    (我们使用两个双引号作为转义来在输出中获得一个双引号 - 相信我,它有效。)

    【讨论】:

    • 您可以从语法高亮中看到这不起作用。你需要" WHERE (((tblEquipment.strDescription) Like '*" & [Forms]![frmSearch]![strSearchBox] & "*'));"" WHERE (((tblEquipment.strDescription) Like ""*" & [Forms]![frmSearch]![strSearchBox] & "*""));"
    猜你喜欢
    • 2015-07-26
    • 2010-10-11
    • 2012-07-03
    • 1970-01-01
    • 2020-01-27
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多