admin

使用Excel VBA,SQL BETWEEN日期查询来查询MS Access

sql

全部 -

我正在尝试使用SQL查询,使用以下代码将Access数据库中的记录提取到Excel VBA用户窗体列表框中:

Sub FillLBBillIDs()
'build bill ID list box with bill IDs available in database, based on client and/or date range
'<---------------------------------------------------Dimension all variables
Dim con As Object, cmd As Object, rst As Object
Dim Path As String, CName As String
Dim FromDate As Date, ToDate As Date
Dim X As Long, Y As Long
'<---------------------------------------------------Define Default Variables
X = 0
CName = AuditParametersFRM.CBOCxName.Value
FromDate = AuditParametersFRM.DTPFrom.Value
ToDate = AuditParametersFRM.DTPTo.Value
'<---------------------------------------------------Define Access connection
Set con = CreateObject("ADODB.Connection"): Set cmd = CreateObject("ADODB.Command"): Set rst = CreateObject("ADODB.RecordSet"):
Path = Sheets("AuditTool").Range("B2").Value
'<---------------------------------------------------Open Access connection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & ";Persist Security Info=False;"
con.ConnectionTimeout = 0: con.CommandTimeout = 0: con.Open: cmd.CommandTimeout = 0: Set cmd.ActiveConnection = con
'<---------------------------------------------------Find all bill IDs in the database which match the selected client and
'<---------------------------------------------------are within the consolidated date range
rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#", con, 1, 3
On Error Resume Next
rst.MoveLast
rst.MoveFirst
Y = 0
Y = rst.RecordCount
AuditToolFRM.LBBillIDs.Clear
If Not Y = 0 Then
    Do Until rst.EOF
'<---------------------------------------------------Build the listbox with the acquired information
        With AuditToolFRM.LBBillIDs
            .AddItem
            .List(X, 0) = rst![BillID]
            X = X + 1
        End With
        rst.MoveNext
    Loop
End If
rst.Close
On Error GoTo 0
con.Close
End Sub

如果我使用大于参数,则此代码可以正常工作,因此:

rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.ConsolidationDate > #" & FromDate & "#", con 1, 3

我已经浏览了本网站上的所有相关问题,找不到任何有效的方法。有任何想法吗?

提前致谢!

12/08/2017 12:54

我做了更多的测试,似乎大于查询也不起作用;它会拉取所有符合第一个条件的记录,而忽略第二个条件,即使使用括号将第二个条件括起来也是如此。这告诉我问题肯定在查询的日期部分中。任何帮助将不胜感激!


阅读 153

收藏
2021-07-01

共1个答案

admin

在访问中

DATE_FIELD BETWEEN #2/2/2012# AND #2/4/2012#

是相同的

DATE_FIELD >=#2/2/2012# AND <=#2/4/2012#

当您还有另一个AND时,请在日期范围语法周围加上括号。

rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND (AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#)", con, 1, 3

2021-07-01