Page 57 - Excel Progamming Weekend Crash Course
P. 57
d540629 ch03.qxd 9/2/03 9:27 AM Page 32
32 Friday Evening
gas in the tank. Some object properties are read-only, meaning that you can determine their
value but not change it (for example, the number of doors). Others are read-write and can
be read as well as changed, such as the radio station.
In contrast, a method is something that the object can do, such as an action it can per-
form. Continuing with the car analogy, its methods would include “speed up,” “turn,” and
“stop.” Many methods take arguments, information that specifies exactly how the method
should work. The “turn” method, for example, might have a “direction” argument that
could be either “right” or “left.”
Notation for properties and methods follows the standard ObjectName.MemberName for-
mat. When a method takes arguments, there are three ways you can do it. The first is to
include the arguments, in parentheses and in the correct order, following the method name:
ObjectName.MethodName(argument1, argument2, ...)
In the rare case of a property that takes arguments, you must also use this syntax. The
arguments must be in the precise order defined by the method definition.
Another way of including arguments in a method call is essentially the same, but omits
the parentheses:
ObjectName.MethodName argument1, argument2, ...
Again, the arguments must be in the correct order.
The final way to include arguments is called named arguments and is perhaps the easiest
and clearest. It makes use of the argument name, as provided in the method definition, and
the := operator, followed by the argument value. Thus:
ObjectName.MethodName argument1name:=argument1value, _
argument2name:=argument2value
Here’s a real example:
MyWorkbook.SaveAs Filename:=”AnnualSales.wks”
There are two advantages to using named arguments. One is having clarity in your code.
Each argument’s name is a description of its purpose and therefore helps you or others
understand code that was written earlier. The other is simplicity. Many methods have lots of
optional arguments, and you may want to call the method with most of the arguments left
at their default values. Without named arguments, the method can identify an argument
only by its position in the argument list, so you have to include placeholders (commas) for
all optional arguments that you are omitting (and using the default value). In other words,
a placeholder is a comma followed by another comma — the omitted argument would go
between the commas if it were included. With named arguments, this is not necessary —
include only those optional arguments that you want to change from the default.
The Importance of Object References
To work with an object, you need a reference to it. This is nothing more than a name used
in code to refer to the object. Sometimes the object already exists, and all your code needs
to do is obtain a reference to it. An example is when your program opens a workbook and