Search code examples
ms-access

How do I prevent an error 2101 in Access when I have a button to save a record on a form?


Here's something I think should work (and I believe I once had it working) in Microsoft Office Access.

I have a single record form with a few bound controls and a button to save the values on the form.

The button's OnClick handler is basically a

private sub btnSave_Click()
     me.dirty = false
end sub

Since I need to check the entered values, there's also a OnBeforeUpdate handler:

private sub form_beforeupdate(cancel as integer)

  if nz(me.SomeControl, "") = "" then
     msgBox("....")
     cancel = true
     exit sub
  end if

  ' ...  more checks ...

end sub

Now, when I click the button, and the handler reaches the me.dirty=false, the execution flow goes to the BeforeUpdate handler, which is expected. Since ComeControl is not filled, cancel is set to true and the sub is exited, which is still expected.

The problem is when the execution flow comes back to the buttons Click handler. The line me.dirty = false stops execution and the Run-time error '2101' The setting you entered isn't valid for this property is thrown.

This is not expected and I actually do believe I had this working.

Anyway, how do I go about having such a save button together with a BeforeUpdate handler?


Solution

  • Do you need to save the record at this point, given that saving is the default for Access? If so, perhaps trapping the error will suit:

    Private Sub btnSave_Click()
    On Error GoTo Err_Handler
    
     Me.Dirty = False
    
    Exit_Here:
         Exit Sub
    
    Err_Handler:
         If Err.Number=2101 Then
           'ignore or message
         Else
            MsgBox Err.Description
         End If
    
         Resume Exit_Here
    End Sub