Читать книгу Excel VBA Programming For Dummies - Dick Kusleika - Страница 78

Taking action with object methods

Оглавление

In addition to properties, objects have methods. A method is an action you perform with an object. A method can change an object’s properties or make the object do something.

This simple example uses the ClearContents method on a Range object to erase the contents of 12 cells on the active sheet:

Sub ClearRange() Range("A1:A12").ClearContentsEnd Sub

Some methods take one or more arguments. An argument is a value that further specifies the action to perform. You place the arguments for a method after the method, separated by a space. Multiple arguments are separated by a comma.

The following example activates Sheet1 (in the active workbook) and then copies the contents of cell A1 to cell B1 by using the Range object’s Copy method. In this example, the Copy method has one argument, which is the destination range for the copy operation:

Sub CopyOne() Worksheets("Sheet1").Activate Range("A1").Copy Range("B1")End Sub

Notice that the worksheet reference is omitted when referring to the Range objects. You can do this safely due to the statement to activate Sheet1 (using the Activate method).

Another way to specify an argument for a method is to use the official name of the argument followed by a colon and an equal sign. Using named arguments is optional, but doing so can often make your code easier to understand, particularly if the method takes many parameters. The second statement in the CopyOne procedure could be written like this:

Range("A1").Copy Destination:=Range("B1")

Figure 4-2 shows the little prompt that appears as I type a statement. That prompt indicates the official name of the argument.


FIGURE 4-2: The VBE displays a list of arguments while you type.

Because a collection is also an object, collections have methods. The following macro uses the Add method for the Workbooks collection:

Sub AddAWorkbook() Workbooks.AddEnd Sub

As you might expect, this statement creates a new workbook. In other words, it adds a new workbook to the Workbooks collection. After you execute this macro, a fresh workbook is the active workbook.

Excel VBA Programming For Dummies

Подняться наверх