从Excel VBA查询MS Access DB - 如果未找到值,如何返回0?

时间:2016-02-10 21:46:22

标签: excel-vba null vba excel

我在excel VBA中查询MS Access数据库。如果DB中没有记录,我需要它在excel中返回0。这是我的代码:

Function CheckIfDateExistInDB(MyDate As Date) As Date
Dim strSql As String

strSql = "SELECT Date FROM AccessDB WHERE Date = #" & MyDate & "#"

Set AccessRS = AccessCN.Execute(strSql)
CheckIfDateExistInDB = AccessRS.Fields(0)
Set AccessRS = Nothing
End Function

请帮忙 - 1)此代码返回" #VALUE!"如果DB中不存在记录,则在excel中。 2)如果记录不存在,则此查询需要很长时间才能运行。 3)如果没有记录,我需要代码返回0(并加速)。

1 个答案:

答案 0 :(得分:1)

在字段检索期间考虑通过recordcount属性有条件地包装记录集:

Dim AccessCN As Object, AccessRS As Object

Set AccessCN = CreateObject("ADODB.Connection")
Set AccessRS = CreateObject("ADODB.Recordset")

AccessCN.Open "DRIVER=Microsoft Access Driver (*.mdb, *.accdb);" _
                & "DBQ=C:\Path\To\Database\File.accdb;"
AccessRS.Open "SELECT Date FROM AccessDB WHERE Date = #" & MyDate & "#", AccessCN

If AccessRS.RecordCount > 0 Then
     CheckIfDateExistInDB = AccessRS.Fields(0)
Else
     CheckIfDateExistInDB = 0
End If

AccessRS.Close

Set AccessRS = Nothing
Set AccessCN = Nothing