Understanding the Differences Between Objects and Collections
Many people get confused about the differences between an object and a collection. Think of an object as a member of a collection. For example, frmHello is a form that's a member of the Forms collection; cmdHello, a command button on frmHello, is a member of the Controls collection of frmHello. Sometimes you want to manipulate a specific object, but other times you want to manipulate a collection of objects.
Manipulating a Single Object
You have already learned quite a bit about manipulating a single object, such as setting the Enabled property of a text box:Me.txtCustomerID.Enabled = False
This line of code affects only one text box and only one of its properties. However, when you're manipulating a single object, you might want to affect several properties at the same time. In that case, it's most efficient to use the With...End With construct, explained in the following section.One method you can use to modify several properties of an object is to modify the value of each property, one at a time:Me.txtCustomerID.Enabled = False
Me.txtCustomerID.SpecialEffect = 1
Me.txtCustomerID.FontSize = 16
Me.txtCustomerID.FontWeight = 700
Contrast this with the following code:With Me.txtCustomerID
.Enabled = False
.SpecialEffect = 1
.FontSize = 16
.FontWeight = 700
End With
This code uses the With...End With statement to assign multiple properties to an object. In addition to improving the readability of your code, the With...End With construct results in a slight increase in performance.
Manipulating a Collection of Objects
A collection is like an array of objects. What makes the array special is that it's defined and maintained by Access. Every collection in Microsoft Access is an object, each with its own properties and methods. The VBA language makes it easy for you to manipulate Access's collections of objects; you simply use the For Each…Next construct which performs the same command on multiple objects.In the "Determining the Type of a Control" section later in this chapter, you learn how to loop through the collection of controls on a form, performing actions on all the command buttons. This illustrates a practical use of a collection. In the following example, you loop through all the open forms, changing the caption of each form:Sub FormCaptions()
Dim frm As Form
For Each frm In Forms
frm.Caption = frm.Caption & " - " & CurrentUser
Next frm
End Sub
This routine uses the For Each…Next construct to loop through each form in the Forms collection, setting the caption of each form to the form's caption concatenated with the current username. As you travel through the loop, the code frm.Caption refers to each member of the Forms collection.