Methods

Whereas properties are the quantifiable characteristics of objects, methods are the actions that can be performed by objects or on objects. If you have a linguistic bent, you might like to think of objects as nouns, properties as adjectives, and methods as verbs. Methods often change the properties of objects. I have a walking method that takes me from A to B, changing my location property. I have a spending method that reduces my bank balance property and a working method that increases my bank balance property. My dieting method reduces my weight property, temporarily.

A simple example of an Excel method is the Select method of the Range object. To refer to a method, as with properties, put the object first, add a period, and then add the method. The following selects cell G4:

Range("G4").Select

Another example of an Excel method is the Copy method of the Range object. The following copies the contents of range A1:B3 to the clipboard:

Range("A1:B3").Copy

Methods often have parameters that you can use to modify the way the method works. For example, you can use the Paste method of the Worksheet object to paste the contents of the clipboard into a worksheet, but if you do not specify where the data is to be pasted, it is inserted with its top-left corner in the active cell. This can be overridden with the Destination parameter (parameters are discussed later in this section):

ActiveSheet.Paste Destination:=Range("G4")

Note that the value of a parameter is specified using :=, not just =.

Often, Excel methods provide shortcuts. The previous examples of Copy and Paste can be carried out entirely by the Copy method:

Range("A1:B3").Copy Destination:=Range("G4")

This is far more efficient than the code produced by the macro recorder:

Range("A1:B3").Select Selection.Copy Range("G4").Select ActiveSheet.Paste

0 0

Post a comment