Excel VBA,ADO 连接,return 日期(如果存在)或上一个可用日期

Excel VBA, ADO connection, return the date if exists, or the previous available date

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

所以我正在构建函数 myfunction(mydate) 应该 return 最大可用日期等于或小于(早于)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

结果应该是

这适用于 excel 电子表格,但会出现错误 "Unable to get Match property of the WorksheetFunction"。是否有另一种方法可以使用此数组获取结果?

您可以试试记录集查找方法:

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

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

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