Category: VBA

Error Catching On Access VBA

11 January, 2008 | Access | No comments

To use error detection on Access you need to use the command On Error GoTo and then give the error label a name. When the code comes across an error it will run the code in the error handling section. The following code will try to open a form that doesn’t exist, when an error occurs the code will print out "Can’t Find Form" to the Immediate window and then exit.

Sub run()
  On Error GoTo ErrHandler
    DoCmd.OpenForm "aNonExistantForm", acNormal, , , acFormEdit, acWindowNormal
  Exit Sub
ErrHandler:
  ' error handling stuff
  Debug.Print "Can't Find Form"
  Exit Sub
End Sub

The name of the error section must be the same as the name you entered when you set up the error section with On Error GoTo. Don’t forget the colon as well as this turns it into a label.

Whilst in the error section the Err object is available to use. This will give you any information about the error that is available to the system. So to get more details information about the error you can print off the description by using the variable Err.Description. From the above example this would print off the text The form name 'aNonExistantForm' is misspelled or refers to a form that doesn’t exist. to the Immediate window.

Of course you might want to do more to the code than just exit. You could use a global function that will send an email or otherwise log the error so you can deal with the issue later. It is always best to deal with errors in a positive way when they happen.

Getting All Form Objects In Access VBA

10 January, 2008 | Access | No comments

In Access all forms are contained as objects in the AllForms collection, which is part of the Application.CurrentProject object. To iterate through them and print them off just load them one by one into a temporary object and use the Name property of the form object to print off its name.
Sub AllForms()
  Dim obj As AccessObject, dbs As Object
  Set dbs = Application.CurrentProject
  ' Search for open AccessObject objects in AllForms collection.
  For Each obj In dbs.AllForms
    ' Print name of obj.
    Debug.Print obj.Name
  Next obj
End Sub

If you want to get a list of all of the active form objects (ie. those forms that are currently open) then use the IsLoaded property for each object.
Sub AllForms()
  Dim obj As AccessObject, dbs As Object
  Set dbs = Application.CurrentProject
  ' Search for open AccessObject objects in AllForms collection.
  For Each obj In dbs.AllForms
    If obj.IsLoaded = True Then
      ' Print name of obj.
      Debug.Print obj.Name
    End If
  Next obj
End Sub