我正在使用Excel VBA从Access数据库中提取数据。我的“选择”和“发件人”语句工作正常。当我添加“ Where”语句时,没有任何结果。你能帮忙吗?!
Dim SDATE As String
Dim EDATE As String
Dim SQLstring As String
SDATE = Application.InputBox("Beginning Date", "Date 1", Format(Date - 31, "MM-DD-YY"))
EDATE = Application.InputBox("Ending Date", "Date 2", Format(Date, "MM-DD-YY"))
SQLstring = "SELECT tblitemhistory.HistDate, tblstockitems.MasterPNo, tblstockitems.ItemDescription, tblitemhistory.HistType, tblitemhistory.HistText, tblitemhistory.HistQty " & _
"FROM tblitemhistory INNER JOIN tblstockitems ON tblitemhistory.StockID = tblstockitems.ItemID" & _
"where (((tblitemhistory.HistDate) between #" & [SDATE] & "# AND #" & [EDATE] & "#"""
getSQLString = SQLstring
我希望在用户输入的两个日期之间提取记录。运行代码时没有错误,但也没有结果。
答案 0 :(得分:0)
尝试从[SDATE]和[EDATE]中除去括号。这是SQL语法,而不是VBA语法。
您可能会考虑将格式更改为mm / dd / yyyy,日期的区域性解释可能会让您头疼。
看到这个:
https://bytes.com/topic/access/insights/575420-literal-datetimes-their-delimiters
**编辑**
我刚刚意识到您并没有终止所有这些括号:(((tblitemhistory.HistDate)
。您不需要任何一个。另外,在结尾加3个引号可能会在查询的末尾添加一个引号,您可能不希望这样,请尝试"where tblitemhistory.HistDate BETWEEN #" & SDATE & "# AND #" & EDATE & "#"
答案 1 :(得分:0)
可能您所在的区域的日期是第一天而不是第一个月。因此,无论输入什么日期范围,该部分都没有数据,因为您不会收到任何错误。
因此,请考虑两项调整:
删除所有格式,并让用户在其所在的任何区域中输入日期,并根据其CPU默认值调整日期。
使用MS Access'QueryDefs进行参数化,而不是在VBA中使用SQL串联,如下所示,使用DAO连接。
Sub RunQuery()
Dim SDATE As Date, EDATE As Date
Dim SQLstring As String
Dim conn As Object, db As Object, qdef As Object
SDATE = Application.InputBox("Beginning Date", "Date 1", Date - 31) ' REMOVE Format()
EDATE = Application.InputBox("Ending Date", "Date 2", Date) ' REMOVE Format()
Set conn = CreateObject("DAO.DBEngine.120")
Set db = conn.OpenDatabase("C:\Path\To\Database.accdb")
' PREPARED STATEMENT (NO DATA) - CAN BE SAVED IN MS ACCESS AS QUERY OBJECT
SQLstring = "PARAMETERS [Prm_SDATE] Date, [Prm_EDATE] Date;" & _
"SELECT i.HistDate, s.MasterPNo, s.ItemDescription," & _
" i.HistType, i.HistText, i.HistQty " & _
"FROM tblitemhistory i " & _
"INNER JOIN tblstockitems s ON i.StockID = s.ItemID" & _
"WHERE i.HistDate BETWEEN [Prm_SDATE] AND [Prm_EDATE];"
' BIND PARAMETERS
Set qdef = db.CreateQueryDef("", SQLstring)
qdef![Prm_SDATE] = SDATE
qdef![Prm_EDATE] = EDATE
' OPEN RECORDSET
Set rst = qdef.OpenRecordset
' DUMP OUTPUT TO EXCEL SHEET
Worksheets("Sheet1").Range("A1").CopyFromRecordset rst
rst.Close: db.Close
Set qdef = Nothing: Set db = Nothing: Set conn = Nothing
End Sub