Closing Forms

If you want to use a button to close a form in Access instead of clicking the X button, you need to write VBA code to close the form. The basic way to do this is by using the following code:

DoCmd.Close

This method of the DoCmd object will close the active object, like your form. It doesn't get much simpler than that. Unfortunately, there is an obscure situation that will cause this code to fail to close the correct form. If you read the help documentation on DoCmd.Close, you'll see that if you don't provide any parameters, it closes the active form. You might assume that the active form is the one containing this code; after all, you just clicked the Close button, so the form must be active. However, there are situations where another form is the active one.

One case is where you have a hidden form on a timer that periodically does something. This is a technique that is often used in automatic log-off functionality, where a hidden form uses a timer to periodically check a table to determine whether it should exit the application. The problem is, when that timer fires and the code in the form checks the table, it becomes the active form. If you're unlucky enough for that to happen right when the Close button is clicked, the wrong form (the hidden one) will close.

Another situation is when the code in your closing routine reaches out and runs code in another form; this can make the other form active at that moment. The solution is to clarify the DoCmd.Close statement, like this:

DoCmd.Close ObjectType:=acForm, ObjectName:=Me.Name

This specifies that a form be closed, specifically the form that this code belongs to. If you get into the habit of using this syntax, the intended form (this one) will always close correctly.

0 0

Post a comment