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

Editing the code by changing cell references

This recipe shows you how to edit coding in the VBA Editor. It is more effective to make changes in the code, rather than deleting an entire macro and recording it again. We're going to start by deleting some redundant lines of code, before showing you how to edit code in order to bring about a visible change on the spreadsheet when the code is executed.

Getting ready

With 02_RecordMacro.xlsx still open, use the keyboard shortcut, Alt + F11, to activate the VBA Editor.

How to do it…

For this recipe, the steps are as follows:

  1. In the VBA Editor, double-click on Module1 to open the code window.
  2. In the code window, select the second line of the executable code. Delete the line of code, as well as the empty line:

    Figure 1.17 – Selected code to be deleted

  3. Switch back to Excel, clear all formatting on the data and run the macro. The result is the same as with the first test.
  4. Next, select all the lines after .HorizontalAlignment = xlCenter. Press Del:

    Figure 1.18 – Selected code to be deleted

  5. Once again, switch back to Excel, clear all formatting on the data, and run the macro. The result is still the same as with the first test.
  6. Finally, change the cell reference in the last line from A1 to G2:

    Figure 1.19 – Cell reference to be changed

  7. For the last time, switch back to Excel, clear all formatting on the data in the spreadsheet, and run the macro. The formatting is done as before, but the focus is on cell G2 and not on A1 this time.

How it works…

Let's understand what just happened.

The Range("A3").Activate line can be deleted because the C1:F2, A3:B7 range is already selected. It is that selection that will be formatted to bold.

When the C3:F8 range is selected, we only want it to be centered. The other lines are automatically added but are redundant, and can, therefore, be deleted.

Instead of ending on cell A1, we change the focus to cell G2.

There's more…

The macro has been recorded, tested, and edited, but we have not saved the file yet. As simple as it may sound, there is a trick to it. Refer to the next recipe to take care of that.

主站蜘蛛池模板: 佛山市| 丘北县| 梁山县| 腾冲县| 余干县| 育儿| 沅陵县| 新巴尔虎左旗| 白山市| 阿克陶县| 平乐县| 法库县| 建宁县| 简阳市| 乌鲁木齐市| 赣榆县| 山阴县| 青浦区| 庆阳市| 靖边县| 靖远县| 连云港市| 宝丰县| 漳浦县| 姜堰市| 朝阳区| 上蔡县| 会同县| 靖江市| 民和| 潞西市| 东乌珠穆沁旗| 姜堰市| 朝阳区| 青岛市| 星座| 博罗县| 阿巴嘎旗| 博野县| 嘉义县| 舟山市|