我打开了一个新的ADODB连接,并设置了一个在第一个字段中包含日期、在第二个字段中具有值的新记录集。
- 2016年1月1日
- 2016年1月2日
- 2016年1月4日
- 2016年1月5日
因此,我正在构建函数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的Match属性"。有没有其他方法可以使用此数组获得结果?
如果你做了多个记录集,你可以试试这个:
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
您可以尝试记录集查找方法:
rst.movefirst
rst.find "datecolumnname >= " & mydate
If rst.BOF = false then
myfunction = rst.fields(0)
Else
Set myfunction = nothing
Endif