简体   繁体   中英

Query MS Access DB from Excel VBA - How to return 0 if no value found?

I'm querying an MS Access database from within excel VBA. I need it to return 0 in excel if no record exists in the DB. This is my code:

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

Please help - 1) This code returns "#VALUE!" in excel if the record does not exist in the DB. 2) If the record does not exist, this query takes a LONG time to run. 3) I need the code to return 0 if no record exists (and speed it up).

Consider conditionally wrapping recordset by recordcount property during field retrieval:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM