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

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.

主站蜘蛛池模板: 海伦市| 金溪县| 互助| 合水县| 苍山县| 台江县| 滨州市| 金沙县| 全椒县| 神木县| 漳州市| 都匀市| 三穗县| 镇康县| 张掖市| 卢龙县| 凤台县| 祁东县| 香河县| 柘城县| 扬州市| 清新县| 三都| 德令哈市| 泰顺县| 诸暨市| 临猗县| 金塔县| 泰宁县| 仪征市| 西藏| 云安县| 泰兴市| 富宁县| 阜宁县| 安丘市| 嘉善县| 丰原市| 韩城市| 桑植县| 中西区|