官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 紫金县| 丹巴县| 塔河县| 洪雅县| 石林| 乌兰县| 蓝田县| 广元市| 井冈山市| 舞阳县| 当涂县| 固始县| 黄浦区| 元氏县| 潮州市| 宝应县| 阜南县| 蒲江县| 汽车| 海口市| 青河县| 灵璧县| 柳江县| 石嘴山市| 沅江市| 尼玛县| 阿瓦提县| 普兰县| 镇原县| 喀喇沁旗| 浏阳市| 南木林县| 萨迦县| 抚顺市| 阜新市| 新密市| 监利县| 枝江市| 胶南市| 五河县| 乌拉特后旗|