I’m trying to write a VBA function that gets a value from an Access table using a SELECT query. Here’s the code:
Function getTableValue(uniqueID As Long, tableName As String, _
idField As String, tableField As String) As Variant
Dim db As Database
Dim rs As Recordset
Dim selectSQL As String
selectSQL = "select * from " & tableName & " where " & idField & "=" & uniqueID
Set db = OpenDatabase(dbPath)
Set rs = db.OpenRecordset(selectSQL)
If rs.RecordCount > 0 Then
rs.MoveLast
rs.MoveFirst
getTableValue = rs.Fields(tableField)
End If
End Function
When the field specified by tableField is a Date/Time type and the field is empty, getTableValue() returns an “Invalid use of Null” error. I thought that having the function return a Variant would allow me to return Null values; what should I do to handle these empty dates?
It turns out that the function’s Null value was being passed to a Date/Time variable. I’ve fixed that by using the following:
While it doesn’t check whether or not
myVarreturns a Date,valueField‘s values are of type Date/Time so it’s ok.