VBA按访问功能按日期搜索

时间:2015-04-06 19:49:31

标签: sql vba syntax-error ms-access-2010

有人可以帮我解决下面的代码。我试图促使用户约会,然后在表格中按日期搜索。我查询的表格具有日期时间格式,但我希望能够按日期搜索。 我能够获得用户输入但我在查询表达式中得到错误"语法错误(缺少运算符)。

 Function cmdInputBox_Click()
    Dim DatePick As Date
    DatePick = InputBox("Enter Date:", "Date", Format(Now(), "dd/mm/yy"))

  Dim strSQL As String


    strSQL = " INSERT INTO PalletMoves " _
        & "SELECT [Pick Area].[From Location], [Pick Area].[Game Number], [Pick Area].[Pallet Number], [Pick Area].[Game Name], [Pick Area].[Shipment Number], [Pick Area].[Box Range], [Pick Area].Cases, [Pick Area].Packs, [Pick Area].Tickets, [Pick Area].[Price Point], [Pick Area].[Delivery Date], [Pick Area].Skids, [Pick Area].[Created Date] " _
        & "FROM [Pick Area] " _
        & "WHERE CAST([Created Date] AS Date) dateDate = '" & DatePick & "';"
DoCmd.RunSQL strSQL

End Function

2 个答案:

答案 0 :(得分:2)

where子句必须如下所示:

"WHERE [Created Date] = #" & DatePick & "#;"

更多信息:https://support.office.com/en-us/article/Examples-of-using-dates-as-criteria-in-Access-queries-aea83b3b-46eb-43dd-8689-5fc961f21762

注意:我需要警告你。当用户删除默认字符串并单击Cancel按钮时,InputBox函数将返回空字符串!您应该在执行进一步的代码(查询)之前检查它。

答案 1 :(得分:0)

您需要将Date值放在#内,同时将其用作MS Access查询中的条件。

strSQL = " INSERT INTO PalletMoves " _
        & "SELECT [Pick Area].[From Location], [Pick Area].[Game Number], [Pick Area].[Pallet Number], [Pick Area].[Game Name], [Pick Area].[Shipment Number], [Pick Area].[Box Range], [Pick Area].Cases, [Pick Area].Packs, [Pick Area].Tickets, [Pick Area].[Price Point], [Pick Area].[Delivery Date], [Pick Area].Skids, [Pick Area].[Created Date] " _
        & "FROM [Pick Area] " _
        & "WHERE [Created Date] = #" & DatePick & "#;"

更多内容请点击此处:https://support.office.com/en-us/article/Examples-of-using-dates-as-criteria-in-Access-queries-aea83b3b-46eb-43dd-8689-5fc961f21762