我正在使用Access数据库,希望对保存记录的时间有更多的控制。我想做的一件事情是检查是否已填写了调用SaveResponse函数的任何形式的所有必填字段。这是我提供的相关代码段。
Private Sub Form_BeforeUpdate(Cancel As Integer)
SaveResponse(Form.Recordset)
End Sub
Public Function SaveResponse(rs As Recordset) As Long
Dim response As VbMsgBoxResult, fld As Field
response = MsgBox("Do you want to save changes to this record?", vbQuestion + vbYesNo, "Save Record")
If response = vbYes Then
For Each fld In rs.Fields
If fld.Required = True And Nz(fld, "") = "" Then
MsgBox "The " & fld.Name & " field is required."
SaveResponse = 2
Exit Function
End If
Next
ElseIf response = vbNo Then
CodeContextObject.Undo
SaveResponse = 1
Exit Function
End If
End Function
运行时,出现错误:“ 3001:Invalid Argument”
我认为我已经将这个问题缩小到我实际检查记录集中给定字段是否为空的位置(以下代码)。
Nz(fld, "") = ""
我没有运气就尝试了以下替代方案...
Nz(fld.Value, "") = ""
Nz(rs.Fields(fld.Name).Value, "") = ""
IsNull(fld.Value)
IsNull(rs.Fields(fld.Name).Value)
我想念什么?如何检查记录集中的必填字段是否为空值?
编辑:下面的新代码处理记录集中尚未存在的新记录,但返回“此集合中未找到3265项”。
Private Sub Form_BeforeUpdate(Cancel As Integer)
SaveResponse(Form)
End Sub
Public Function SaveResponse(frm as Form) As Long
Dim response As VbMsgBoxResult, rs as Recordset, ctl As Control, fldName As String
response = MsgBox("Do you want to save changes to this record?", vbQuestion + vbYesNo, "Save Record")
If response = vbYes Then
Set rs = frm.Recordset
For Each ctl In frm.Controls
fldName = ctl.ControlSource
If rs(fldName).Required And Nz(fldName, "") = "" Then
MsgBox "The " & fldName & " field is required."
SaveResponse = 2
Exit Function
End If
Next
ElseIf response = vbNo Then
CodeContextObject.Undo
SaveResponse = 1
Exit Function
End If
End Function
这一次,我相信问题出在If rs(fldName).Required
行。有什么想法吗?