在where子句中使用变量

时间:2016-02-08 15:50:35

标签: sql-server ms-access access-vba ms-access-2007 ms-office

使用以下代码:

Dim RCMSql As String
    RCMSql = "SELECT [Range Card Master Mailer].Master_ID," & _
    "[Range Card Master Mailer].MaxOfDate_of_Transaction," & _
    "[Range Card Master Mailer].FirstName," & _
    "[Range Card Master Mailer].LastName," & _
    "[Range Card Master Mailer].Email_Address," & _
    "[Range Card Master Mailer].Address_Line_1," & _
    "[Range Card Master Mailer].Phone_Number_1," & _
    "[Range Card Master Mailer].Phone_Number_2," & _
    "[Range Card Master Mailer].Date_Sent," & _
    "[Range Card Master Mailer].RedeemFlag " & _
    "FROM [Range Card Master Mailer] " & _
    "WHERE ((([Range Card Master Mailer].Master_ID) = '002366'))"
     RCMRs.Open RCMSql  

这执行得很好,但是如果我更改where子句以使用打开表单上的文本框中的值,我会收到错误"没有为一个或多个参数提供值"

"WHERE ((([Range Card Master Mailer].Master_ID) = Me!scanTxtBox))"

我已尝试过至少十几种变体,但无法将其付诸实践

由于

JPL

2 个答案:

答案 0 :(得分:0)

我相信这就是你要找的东西:

Dim RCMRs As ADODB.Recordset
Dim RCMSql As String
RCMSql = "SELECT [Range Card Master Mailer].Master_ID," & _
    "[Range Card Master Mailer].MaxOfDate_of_Transaction," & _
    "[Range Card Master Mailer].FirstName," & _
    "[Range Card Master Mailer].LastName," & _
    "[Range Card Master Mailer].Email_Address," & _
    "[Range Card Master Mailer].Address_Line_1," & _
    "[Range Card Master Mailer].Phone_Number_1," & _
    "[Range Card Master Mailer].Phone_Number_2," & _
    "[Range Card Master Mailer].Date_Sent," & _
    "[Range Card Master Mailer].RedeemFlag " & _
    "FROM [Range Card Master Mailer] " & _
    "WHERE ((([Range Card Master Mailer].Master_ID) = '" & _
    Replace(Me!scanTxtBox, "'", "''") & "'))"
RCMRs.Open RCMSql

答案 1 :(得分:0)

在您的代码中将局部变量定义为字符串

如果你发布的第一个代码运行,Master_ID被定义为字符串,那么,用

定义一个局部变量
Dim localScanTxtBox as string

并设置它(如果在您的scanTxtBox中有一个6字符串字符串):

localScanTxtBox = Me!scanTxtBox

或,将其转换为包含以下内容的6位数字符串:

localScanTxtBox = format$(Me!scanTxtBox,"000000")

然后将您的where statement写为:

WHERE ((([Range Card Master Mailer].Master_ID) = '" & localscanTxtBox & "'))

希望这有帮助