我正在尝试编写一个 VBA 函数,该函数使用 SELECT 查询从 Access 表中获取值。这是代码:
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
当 tableField
指定的字段为 Date/Time 类型且该字段为空时,getTableValue()
返回“无效使用 Null”错误。我认为让函数返回一个 Variant 将允许我返回 Null 值;我应该如何处理这些空日期?
最佳答案
事实证明,函数的 Null 值被传递给日期/时间变量。我已经使用以下方法解决了这个问题:
dim myDate as date
dim myVar as variant
myVar=getTableValue(idNum,"thisTable","idField", "valueField")
if isNull(myVar) then
myDate=0
else
myDate=myVar
endif
虽然它不检查 myVar
是否返回日期,但 valueField
的值是 Date/Time 类型,所以没问题。
关于ms-access - "invalid use of null"用于返回变体的 vba 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7891921/