Writing Code Behind Forms and Reports

Before you dive head first into VBA, you might want to get your feet wet by writing some basic code in a form. Every object on a form has a number of events you can respond to through VBA. Most objects or controls have a click event, a change event, and enter and exit events, just to name a few. You can add code to any of these events and that code will run in response to a user's actions on your form.

Open an Access database and view a form in design mode. To build code in response to the Click event of a command button, click once to select the control and then display the Properties for the control by clicking the Property Sheet icon on the Ribbon or by right-clicking the control and choosing Properties. Once the Properties are visible, click the Event tab. Choose the On Click event property in the Property Sheet and click the Ellipses button (...) next to the Event property. Choose Code Builder from the dialog box that appears to display the VBA Editor, as shown in Figure 2-2.

Figure 2-2

You'll notice two differences between Figure 2-1 and Figure 2-2. First of all, the Property Sheet shows all of the properties for the control you selected on your form. From this view you can change any number of properties of the control including size, ControlTipText, and Tablndex. The second difference is subtle; there's a new heading, Microsoft Office Access Class Objects, in the upper-left corner of the Project Explorer window. Under that heading is the name of the loaded form that contains the control you're currently working with.

The code window displays the name of the control you're working with and the event you choose. Whenever you choose to build code, a subroutine (sub) is created for you automatically. A function, the other main type of code block you'll write, is used when your code needs to return a value. Because you're writing code in response to an event on the form, you're not actually returning a value. You might update the value of the control on the form within the sub, but the actual sub itself doesn't return a value.

Other than the differences listed previously, the VBA Editor used to build code in response to a control's event is identical to that available in a module. The next chapter goes into detail about the various programming components you'll need to work in VBA.

Was this article helpful?

0 0

Post a comment