【问题标题】:Excel VBA, ADO connection, return the date if exists, or the previous available dateExcel VBA、ADO 连接,如果存在则返回日期,或上一个可用日期
【发布时间】:2016-04-06 23:34:43
【问题描述】:

我打开了一个新的 ADODB 连接,并设置了一个新记录集,该记录集在第一个字段中具有日期,在第二个字段中具有值。

  • 01/01/2016
  • 2016 年 2 月 1 日
  • 04/01/2016
  • 2016 年 5 月 1 日

所以我正在构建函数myfunction(mydate),它应该返回等于或小于(早于)mydate 的最大可用日期:

myfunction(mydate as date)
Dim CurrentDate as Date

Set rst = cn.Execute("SELECT * FROM tbl1 ORDER BY dates;")
CurrentDate = worksheetfunction.INDEX(rst.Fields(0),worksheetfunction.MATCH(CDate(CurrentDate),rst.Fields(0), 1))

myfunction = CurrentDate
end function

结果应该是

  • myfunction("02/01/2016") = 02/01/2016
  • myfunction("03/01/2016") = 02/01/2016

这适用于 excel 电子表格,但它会给出错误“无法获取 WorksheetFunction 的匹配属性”。有没有其他方法可以使用这个 Array 获得结果?

【问题讨论】:

  • 您可以在 SQL 中使用 WHERE 子句吗?也许是TOP?
  • 问题是recordset应该用于几个功能,所以我不能使用WHERE..这是我的代码的简短版本。
  • 现在您只传递一个值(Fields(0) 作为 Match 的第二个参数,其中需要一个值数组,这可能就是抱怨的原因。
  • 好的,但 '0' 表示第一列,rst.Fields(0) 不是数组吗?
  • 不,表示记录集当前行的第一个字段。

标签: vba excel ado adodb


【解决方案1】:

如果你做多个记录集,你可以试试这个:

Function myfunction(mydate as date) as date
    Dim CurrentDate as Date
    Set rst = cn.Execute("SELECT TOP 1 * FROM tbl1 WHERE (dates<=" & Format(mydate, "#mm/dd/yyyy#") & ") ORDER BY tbl1.dates DESC;")
    if not rst.EOF then
        CurrentDate = rst.Fields(0)
    else
        'No record found
    endif
    myfunction = CurrentDate
end function

【讨论】:

  • 但是我有一个问题。如果我打开一个连接并执行整个记录集,并在函数中使用过滤器,这会比我每次都执行数据更快吗?
【解决方案2】:

你可以试试recordset find方法:

rst.movefirst
rst.find "datecolumnname >= " & mydate
If rst.BOF = false then
  myfunction = rst.fields(0)
Else
  Set myfunction = nothing
Endif

【讨论】:

  • Find 方法希望能够向后移动。尽管我已将记录集设置为动态模式,但仍会出现错误“行集不支持向后滚动”:rst.CursorType = adOpenDynamic
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多