Chapter 3: Programming Applications Using Objects


This chapter explains the basic concepts of the object-oriented programming environment, such as using objects in your programs. You will learn the definition of properties, methods, and events, and when to use each one. Because the code is encapsulated into objects with properties, methods, and events available for the objects - a concept called object-oriented programming (OOP)- you can build reusable objects that save a lot of development time. Coding is simplified because the system is organized into smaller sets of interrelated objects, instead of one huge object. Your code will be easier to maintain because it will be easier to understand.

Object-oriented programming is a scary concept for most people, but this chapter demonstrates that it’s really not that complicated. After covering basic object-oriented programming concepts, you will also learn about several Microsoft Access objects and how to use them. Chapter 4 covers cover object-oriented programming in greater detail.

Tip 

You may want to create a new database for use with examples in this chapter. From within Access, click the Office Button on the top left and select New. Enter the database file name as Ch3CodeExamples in the panel on the far right side, and click Create. You can also simply click the New Database link when you first launch Access.

Note that the file menu no longer says the word “File,” but has a circular graphic in the upper-left corner of the screen called the Office Button.

Elements of an Object

Objects are all the things that make up your Access database, such as forms, reports, modules, macros, and tables. Each object has properties that determine its behavior or appearance, as well as methods that determine which actions can be taken upon it. Objects also respond to events that are triggered by actions taken by the user or caused by the system.

Some people tend to confuse a collection with an object. A collection comprises multiple objects. Thus, an object can be a member of a collection. Sometimes you may want to manipulate a specific object (for example, a particular form), whereas other times you may want to manipulate a collection of objects (all the forms in your database). Let’s now turn to some of the most important concepts in the object-oriented programming world: properties, methods, and events.

What Is a Property?

Properties are characteristics of an object that determine its behavior or appearance. Examples of properties include the name, caption, or size of a control. Figure 3-1 shows various properties of a Form. This dialog box can be displayed when the Form is in design view and you select the Design ribbon image from book Property Sheet or press Alt+Enter. Note that some of the properties listed in the figure have selectable Yes/No values, some are text input fields like the Caption property, and others have different choices you can select from a drop-down list.

image from book
Figure 3-1

After setting the preceding Caption property to Ch 3 Test Form for this particular form and running the form, notice how the caption of the form (shown in Figure 3-2) is now set to the value that was in the Properties dialog box.

image from book
Figure 3-2

You can also select other objects on the form in the object drop-down list of the Properties Window, such as text box controls or labels, as shown in Figure 3-3.

image from book
Figure 3-3

As shown earlier, selecting another object from the list in the Properties dialog box allow you to view and modify its properties. Various objects share many of the same properties. For example, forms, text boxes, and labels all have a Caption property, as well as a Name property.

Tip 

The Properties Window can be used to view and modify properties as well as events. This concept will be discussed later in the chapter.

The property values that are set in the Properties dialog box, such as the Caption property shown previously, are called design time settings. Design time settings are those you specify at design time that become the starting value settings for that object. The starting value can be modified at runtime in your VBA code, or at a later time in design view. For example, to change the Caption property of the preceding form at runtime while the program executes, you could use the following VBA command:

  Forms.Item("frmTestProperties").Caption = "New caption goes here." 

In addition to the Properties dialog box, another way to see the available properties for an object is by typing VBA code in the Visual Basic Editor. Figure 3-4 shows that as you type the name of an existing object and press the period key, the list of properties available for that object is displayed.

image from book
Figure 3-4

This feature is very helpful because it keeps you from having to memorize the exact syntax of every property. You just look up a property as you write your code.

The values in the list on Figure 3-4 are all properties, as is indicated by the icon showing a hand holding a card:

image from book

Other items can be present in the drop-down list as well, as I discuss later in this chapter. For now, be aware that you can see a list of properties available for an object within the Code window in the Visual Basic Editor (VBE).

Some objects are visual - such as forms, text boxes, labels, and reports. Other objects are not visual. The user sees nothing when those objects are used. An example of a nonvisual object is a recordset that holds data from a database. Although you may later display data from the recordset on a form, the object itself does not have a visual presence. Both visual and nonvisual objects can have properties.

Yet another way to view the properties available for an object is by using the Object Browser, discussed later in this chapter.

What Is a Method?

Methods are actions that can be taken on an object. They are really sub procedures or functions that are called to perform a particular action. You do not see the code behind sub procedures or functions when using existing Access objects, but they are there. An example of a method you have already used is:

  Debug.Print 

The programmers who wrote Microsoft Access created a Debug object to allow you to interact with the Immediate Window, as you have already done to test your code. Somewhere in the source code for the Debug object is a sub procedure or function called Print that receives the message to print as a parameter and then has code for displaying the message in the Immediate Window. Because Microsoft does not give you the source code for Microsoft Access, you do not see this code - but it’s there. This is also true for objects created by other third parties - a sub procedure or function is behind the method.

Let’s look at an example of how you can see what methods are available for an object. In the code window in the VBE (see Figure 3-5), you can type the object name followed by a period, just as you did before. You get a drop-down list that shows the available methods. Recall from the prior section, you can also use this feature to view the properties available for an object.

image from book
Figure 3-5

In the preceding example, you can see that the Recordset object has properties such as Name and NoMatch, but it also has various methods, such as MoveLast and MoveNext. You can tell whether the item in the list is a property or method based on the icon displayed to the left. You might say the icon for methods looks like a brick in motion:

image from book

You might describe the icon differently, but the point is that this icon indicates that the item in the list is a method. Recall that the hand holding the card is the icon for the Properties window. Another way to see the methods and properties available for an object is to use the Object Browser, as you will see later in this chapter.

What Is an Event?

Events are triggered by actions taken by the user and the application, such as changes to data, mouse movements, or the opening of a form. You use VBA code or macros to respond to events. In other words, you link up the code you write with the user interface of your application through events. For example, you specify which VBA procedure or function to run when a particular event happens. This concept was illustrated briefly in Chapter 2 when you created new procedures and functions. Remember that you tied an event to a procedure so that the procedure would run? Let’s look at some additional examples so this important concept will become totally clear.

One way to view a list of events available for a control is from the Properties dialog box that you saw earlier. As you recall, you can select the Design ribbon image from book Property Sheet from a designer, such as the form or report designer, to view the Properties dialog box. Events for form and report objects, such as controls, can be located by selecting the object and then viewing the Event tab of the Properties dialog box. Figure 3-6 shows the Event tab of the Properties dialog box for a form.

image from book
Figure 3-6

Notice how various types of events are listed. These events allow you to specify when the VBA code you write should execute. You actually have three options for how the event can execute. When you select a particular event from the list and click the Ellipsis button (), a dialog box appears that gives you the option to use the Expression Builder, the Macro Builder, or the Code Builder.

In all the examples so far, you have used the Code Builder because this is a book about VBA code. If you choose Expression Builder, the value displayed in the Properties dialog box will be "=expression", where expression is the expression that was entered in the Expression Builder window. If Macro Builder is chosen, the value is the name of the macro. If Code Builder is chosen, the value will be "[Event Procedure]".

Like properties, various objects often have many or all the same events in common. For example, suppose that you have a form with a text box named txtName (that is, with the Name property set to txtName) that you will use to display a message to the user anytime the On Key Press event occurs. First, select the txtName text box on the form, and then select the Event tab of the Properties dialog box for the text box. Because you want to create an event procedure, select the Event Procedure option from the list that is shown in Figure 3-7 and then click the Ellipsis () button. If you click the Ellipsis () button without selecting the Event Procedure option, you will be prompted to select Code Builder from the list of three options.

image from book
Figure 3-7

When you click the Ellipsis button (), the VBE opens with a new empty procedure created for the KeyPress event. Suppose that the following code is added to the KeyPress event for the txtName text box object:

  Private Sub txtName_KeyPress(KeyAscii As Integer) MsgBox "The KeyPress event just fired" End Sub 

When the form runs and something is typed into the txtName field, the message in Figure 3-8 is displayed.

image from book
Figure 3-8

Notice that the event fires before you see the value in the text box on the form. Other examples of events commonly used are On Click, On Double Click, and On Open. So many types of events are available for a particular object that it is impossible to cover them all in this chapter. However, I hope you understand that an event allows you to hook up your forms and reports with the VBA code that you write based on certain events that occur in the application. I present another example momentarily, just to make sure you are clear on the difference between properties, methods, and events.

Try It Out-Using Properties, Methods, and Events

image from book

It’s your turn now to try your hand at an example that uses properties, methods, and events. As you work, try to keep track of which items are properties, which are methods, and which are events. You can check your answers when I explain the example.

  1. If you have not already done so, create a new database for use with examples in this chapter. To do so, select Office Button image from book New image from book Blank Database. Specify the file name as Ch3CodeExamples and click the Create button. You can close the empty table that opens by default, as you will not be using a table in this example.

  2. Add a new form to the database. Select the Create ribbon and then the Blank Form icon to create a new form. To switch to design view, select the Format ribbon, and then Design View from the View list.

  3. On the new form, use the ToolBox to select and draw a text box control and a command button on the form, as shown in Figure 3-9. The ToolBox is displayed on the Design ribbon, in the Controls area. You can select Cancel to the wizard dialog boxes that appear.

    image from book
    Figure 3-9

  4. Select the text box control. Select the Design ribbon image from book Property Sheet to view the Properties dialog box if it is not already displayed. From the Properties dialog box for the text box control, select the All tab, and change the Name property to txtDateOfBirth.

  5. Select the label. From the Properties dialog box, change the Name property of the label to lblDateOfBirth. Change the Caption property of the label to Enter Date of Birth:

    Tip 

    You may need to resize the label to display all its contents.

  6. Select the Command button. From the Properties dialog box, change the Name property of the Command button to cmdCalculate, and change the Caption property to Calculate. The form should now look like the one shown in Figure 3-10.

    image from book
    Figure 3-10

  7. Close the form to save it, and when prompted, specify the name frmTestObjects for the form. Reopen the form by selecting it in the Navigation Pane, and switch back to design view by selecting Home ribbon, and then Design View from the View list.

  8. Select the txtDateOfBirth text box again. Select the Event tab of the Properties dialog box, and locate the On Exit event. Select the Code Builder option to open VBE to write code for the event. One way to do so is to choose Event Procedure in the drop-down list and then click the ellipsis (). You can also select the Ellipsis button and then choose Code Builder from the dialog box that appears. In either case, add the following code to the Exit event:

      Private Sub txtDateOfBirth_Exit(Cancel As Integer) 'if the user did not enter a date, then 'display an error and set the focus back 'to the date of birth text box control. If Not IsDate(txtDateOfBirth.Text) Then     MsgBox "You must enter a date for the Date of Birth field."     txtDateOfBirth.SetFocus     Cancel = True End If End Sub 

  1. Select the cmdCalculate command button. On the Event tab of the Properties dialog box, select the On Click event, then click the ellipsis, then Code Builder, and add the following code to the newly created event procedure as shown here:

      Private Sub cmdCalculate_Click() 'declare local variable for month of birth Dim intMonthOfBirth As Integer 'convert the value in the text box to a 'month and assign the value to the month  'of birth variable intMonthOfBirth = DatePart("M", CDate(txtDateOfBirth)) 'display a message to the user regarding 'the month of birth MsgBox "Month you were born: " & intMonthOfBirth End Sub 

  2. Click the Save button from the toolbar to save all the changes. Return to the frmTestObjects form in Access and click the Save button to save all changes on the form. Run the form by clicking the Home ribbon and clicking the Form View item on the View list.

  3. Enter something in the text box other than a date (see Figure 3-11).

    image from book
    Figure 3-11

  4. Now, click the Calculate button. The message should be similar to the one shown in Figure 3-12.

    image from book
    Figure 3-12

  5. After you click the OK button, focus returns to the Date of Birth text box field. Type your date of birth (as shown in Figure 3-13).

    image from book
    Figure 3-13

  6. Click the Calculate button. You should get a message box similar to the own shown in Figure 3-14.

    image from book
    Figure 3-14

How It Works

You first created a new database and a form with a text box control and a command button control. Next, you used the Properties dialog box to specify various properties for the objects. You then created two event procedures, also called “event handlers,” in the Visual Basic Editor by launching the Code Builder from the Properties dialog box. The first event procedure was for the Exit event of the txtDateOfBirth text box. The Exit event procedure accepts a Cancel variable as a parameter by default.

  Private Sub txtDateOfBirth_Exit(Cancel As Integer) 

The code will evaluate the value input by the user in the text box, and, if the format is not in a date format, a message is displayed to the user using the msgbox function.

 'if the user did not enter a date, then 'display an error and set the focus back 'to the date of birth text box control. If Not IsDate(txtDateOfBirth.Text) Then     MsgBox "You must enter a date for the Date of Birth field." 

The focus is then set back to the txtDateOfBirth text box, using the SetFocus method of the text box:

  txtDateOfBirth.SetFocus 

The Cancel parameter is then set to True to indicate that the event processing should stop because a problem exists. If you forget to set the Cancel parameter to True, other events that you may not want to fire will do so because the error occurred.

  Cancel = True 

The next event you added was the Click event for the cmdCalculate command button. The Click event first declares a local variable and then converts the value entered in the txtDateOfBirth text box to a month and stores that value in the local variable.

 Private Sub cmdCalculate_Click() 'declare local variable for month of birth Dim intMonthOfBirth As Integer 'convert the value in the text box to a 'month and assign the value to the month 'of birth variable intMonthOfBirth = DatePart("M", CDate(txtDateOfBirth)) 

The code for displaying a message to the user is then listed. In this case, the message is created by concatenating the phrase "Month you were born: " with the value in the variable.

  'display a message to the user regarding 'the month of birth MsgBox "Month you were born: " & intMonthOfBirth 

When you ran the form, you first entered an invalid date value in the text box and then clicked the Calculate button. The Exit event for the text box ran first and evaluated the value that you entered. Because the value was not a date, the error message was displayed, indicating that a date is required, and the mouse was positioned by the set focus event back to the txtDateOfBirth text box.

The second time, you entered a correct date value in the text box field and clicked the Calculate button. This time, the Exit event for the text box ran again but did not have any problems, so the application continued and processed the Click event for the Calculate button. The Click event procedure extracted the month from the date value you entered and then displayed that month to you in a message box.

It’s now time for the quiz. Did you keep track of all the properties, methods, and events used in the example? If so, compare your list to the one that follows.

Open table as spreadsheet

Type

Object

Property, Method, or Event

Property

txtDateOfBirth (text box)

Name

Property

lblDateOfBirth (label)

Name

Property

lblDateOfBirth (label)

Caption

Property

cmdCalculate (command button)

Name

Property

cmdCalculate (command button)

Caption

Event

txtDateOfBirth (text box)

On Exit

Event

cmdCalculate (command button)

On Click

Method

txtDateOfBirth (text box)

Set Focus

See, that wasn’t so difficult, was it?

image from book




Beginning Access 2007 VBA
Beginning Access 2007 VBA
ISBN: 0470046848
EAN: 2147483647
Year: 2004
Pages: 143

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net