将VBA中的Empty / Null Date变量传递给SQL UPDATE语句

时间:2014-07-03 17:23:49

标签: sql excel vba ado

我有一个带有各种文本框的Excel用户表单,有些是输入日期的字段。然后,用户可以保存他们的条目。

此时,我通过ADO连接连接到访问后端。用户输入的值将传递给SQL字符串,例如

strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _
        "tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _
        "tblDECONVERSION_DATA.DateRecieved = #" & Format(NewBusiness_WorkQueue.Decon_DateRecieved, "mm/dd/yyyy") & "#, " & _
        "tblDECONVERSION_DATA.WireDate = #" & Format(NewBusiness_WorkQueue.Decon_WireDate, "mm/dd/yyyy") & "#, " & _
        "tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & "', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _
        "WHERE (((tblDECONVERSION_DATA.CaseID)=" & ID & "));"

        adoRecSet.Open Source:=strSQL, ActiveConnection:=dbconnect, CursorType:=adOpenDynamic, LockType:=adLockOptimistic

但是,某些日期字段可以留空,这意味着例如NewBusiness_WorkQueue.Decon_DateRecieved变量为空。这会导致语法错误。如何在VBA和访问数据库都接受的SQL语句中传递Null或Empty日期变量?

1 个答案:

答案 0 :(得分:2)

strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & _
          NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _
        "tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _
        "tblDECONVERSION_DATA.DateRecieved = " & _
           DateOrNull(NewBusiness_WorkQueue.Decon_DateRecieved) & ", " & _
        "tblDECONVERSION_DATA.WireDate = " & _
           DateOrNull(NewBusiness_WorkQueue.Decon_WireDate) & ", " & _
        "tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & _
         "', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _
        "WHERE tblDECONVERSION_DATA.CaseID=" & ID & ";"

示例功能:

Function DateOrNull(v) As String
    Dim rv as String
    If IsDate(v) Then
        rv = " #" & Format(v, "mm/dd/yyyy") & "# "
    Else
        rv = " null "
    End If
    DateOrNull = rv
End Function