Putting Code in a Form

Running a code routine directly is a bit awkward. At least when you run a macro directly, you can launch it from the navigation pane or use a handy button in the ribbon. Neither option is available with VB code. Instead, you need to open the Visual Basic editor, choose the right module, scroll to the right subroutine, and then click Run. No one actually takes this approach, because it’s just too tedious.

Fortunately, there’s a better approach. You can place code in a form, and then set it to run automatically when something important happens. The following sections explain how.

Responding to a Form Event

Instead of running code routines straight from the editor, Access fans wire them up to form events, just as you can with macros. Here’s how you can try this out:

  1. Open a form in Design mode.

    The fastest way is to right-click a form in the navigation pane, and then choose Design View.

  2. Add a new button.

    To do so, choose Forms Tools | Design→Controls→Button, and then draw the button onto your form.

  3. When the Button wizard begins, press Esc to cancel it.

    You don’t need to create a macro for your button. Instead, this button will be powered by pure VB code.

  4. If the Property Sheet isn’t currently visible, then choose Forms Tools | Design→Tools→Property Sheet.

  5. In the Property Sheet, choose the Other tab, and then set the Name property to give the button a good name.

    Access uses the button name to name the subroutine for your button. It’s much easier to remember ...

Get Access 2010: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.