在查询的WHERE部分中使用Excel变量通过SQL在Excel VBA中进行查询

时间:2017-02-28 14:48:15

标签: sql excel-vba access vba excel

我希望能够在一组数据中查找最小/第一个日期,然后在Access中运行一个查询,该查询将从当天开始删除某个表中的所有数据。

到目前为止我所拥有的是:

Sub upload()
 Last = ActiveSheet.UsedRange.Rows.Count
 Dim LastOrderDate As Date
 Dim LastOrderDateYear As Integer
 Dim LastOrderDateMonth As Integer
 Dim LastOrderDateDay As Integer

 FirstOrderDate = Range("D2")
 FirstOrderDateYear = Year(FirstOrderDate)
 FirstOrderDateMonth = Month(FirstOrderDate)
 FirstOrderDateDay = Day(FirstOrderDate)

 'Import Data to Benji's Ecommerce Database
 ssheet = Application.ActiveWorkbook.FullName
 Set acApp = CreateObject("Access.Application")
     acApp.OpenCurrentDatabase ("X:\ECommerce Database.accdb")
     acApp.Visible = True
     acApp.UserControl = True
     acApp.DoCmd.RunSQL "DELETE * FROM [OrdersDetailed] WHERE Day([OrderDate])=""&FirstOrderDateDay&"" And Month([OrderDate])=""&FirstOrderDateMonth&"" And Year([OrderDate])=""&FirstOrderDateYear&"""
    acApp.DoCmd.TransferSpreadsheet 0, 9, "OrdersDetailed", ssheet, True, "B1:V" & Last
    acApp.CloseCurrentDatabase
    acApp.Quit
Set acApp = Nothing

End Sub

但是它没有删除任何内容,它运行正常,但是Access中出现了消息框,表示正在删除0条记录。

这可能吗?

我是否需要使用不同的语法来输入变量?

由于

畚箕

1 个答案:

答案 0 :(得分:0)

尝试将runSQL字符串更改为:

acApp.DoCmd.RunSQL "DELETE * FROM [OrdersDetailed] WHERE Day([OrderDate])='" & FirstOrderDateDay & "' And Month([OrderDate])='" & FirstOrderDateMonth & "' And Year([OrderDate])='" & FirstOrderDateYear & "'"