【问题标题】:Excel ADODB Query Dates for year 20212021 年的 Excel ADODB 查询日期
【发布时间】:2021-05-20 15:05:59
【问题描述】:

我正在尝试在 Excel 列中查询日期(例如,这是 2021 年,然后只从列中检索 2021 年的日期) 这就是我所拥有的

    CurrMonth = Format$(Date, "m/d/yyyy")
    PrevMonth = Format$(Date - Day(Date), "m/d/yyyy")
    sSQL = "SELECT * " & _
           "FROM [TEST2$] AS M  " & _
           "WHERE M.[something] = '" & rs.Fields("something").Value & "' AND " & _
           "      M.[Date] BETWEEN #" & PrevMonth & "# and #" & CurrMonth & "#" & _
          

【问题讨论】:

  • 你得到什么输出?或者什么错误信息?
  • 您的示例底部似乎也缺少代码
  • "' AND Year(M.[Date]) = " & Year(Date)?
  • 我仍在获取 2020@d0little 的记录
  • ADODB.Command 与实际的Parameter 对象一起使用,将实际的Date 值分配给参数值,将字符串连接替换为? 参数(去掉所有分隔符),以及您不必再担心日期格式了。 SQL 命令字符串应类似于 "SELECT m.* FROM [TEST2$] m WHERE m.[Something]=? AND m.[Date] BETWEEN ? AND ?;"

标签: sql excel vba


【解决方案1】:

当您使用 ADODB 向数据库服务器发送查询时,您应该永远不必处理字符串连接以及字符串和日期文字分隔符。

改为使用正确参数化的Command 并向服务器发送constant 命令字符串:

'SQL string is a compile-time constant that NEVER includes any kind of user inputs:
Const sql As String = "SELECT m.* FROM [TEST2$] m WHERE m.[Something]=? AND m.[Date] BETWEEN ? AND ?;"

Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = yourAdodbConnectionInstance
cmd.CommandType = adCmdText
cmd.CommandText = sql

'now append the positional parameters in order; use an actual Date value (not a String) for an adDate parameter:
cmd.Parameters.Append cmd.CreateParameter(...)
cmd.Parameters.Append cmd.CreateParameter(...)
cmd.Parameters.Append cmd.CreateParameter(...)

'now invoke .Execute and retrieve the results recordset:
Dim results As ADODB.Recordset
Set results = cmd.Execute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2021-08-21
    • 2014-10-03
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多