Associating methods with objects

So, what is a method, and what is its connection with objects? Objects have properties, as we have seen, while a method is something an object does. A method is a specific piece of code you type after an object. It's like an instruction to the object: copy (the cell object), print (the sheet object), or select (the range object). In this recipe, we will use three basic methods: Activate, Copy, and ClearContents. In this recipe, we will copy content from one selection to another.

Getting ready

Make sure that a blank workbook is active in Excel. Type the words Monday, Tuesday, and Wednesday into cells A1, B1, and C1, respectively.

How to do it…

  1. Press Alt + F11 to activate the VBA Editor.
  2. In the Project window of Explorer, double-click Sheet1 under Book1. The corresponding code window will appear.
  3. Type the following code into the code window:

    Sub CopyCell()

          Worksheets("Sheet1").Activate

          Range("A1:C1").Copy Range("A2")

    End Sub

    Run the macro, and then press Alt + F11 to switch back to Excel. Observe how the content of the three cells has been copied to the following row.

  4. Press Alt + F11 to activate the VBA Editor again.
  5. Under the CopyCell Sub procedure, press Enter to create a new line. Type the following code:

    Sub RangeClear()

          Range("A1:C1").ClearContents

    End Sub

  6. Press F5 to run the code, and then press Alt + F11 to switch back to Excel.
  7. Whatever values you had in the range A1 to C1 have been cleared.

How it works…

Cells A1 to C1 each contained a value. The CopyCell Sub procedure first activated Sheet1, and then used the Copy method to copy the contents of cells A1, B1, and C1 to cells A2, B2, and C2.

Following this, we also saw how we can use the RangeClear Sub procedure to clear the content from cells A1, B1, and C1.