Excel VBA,ADO连接,返回date如果存在,或者上一个可用date

我打开了一个新的ADODB连接,并设置了第一个字段中的date和第二个字段中的值的新logging集。

  • 2016年1月1日
  • 2016年2月1日
  • 2016年4月1日
  • 2016年5月1日

所以我build立函数myfunction(mydate) ,应该返回等于或小于(早于)mydate的最大可用date:

 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的匹配属性”。 有没有另一种方法来获得使用此数组的结果?

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

 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 

您可以尝试logging集查找方法:

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