麻烦使用"喜欢"在VBA for Access 2013中的SQL语句中

时间:2016-08-11 17:01:13

标签: vba ms-access sql-like

我已经阅读了数百个问题和答案,但我似乎无法让它发挥作用。我试图使用此SQL语句为列表框设置rowsource ...

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"使用表单上的未绑定文本框。

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

1 个答案:

答案 0 :(得分:2)

*也意味着“乘以两件事”(例如x * y),这样当您尝试将两个字符串相乘时,错误格式化的代码会给您一个类型错误(因为,当然,这没有任何意义!)

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

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

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