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

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.

主站蜘蛛池模板: 宁陵县| 阿巴嘎旗| 锡林郭勒盟| 荥经县| 平利县| 华安县| 枞阳县| 西和县| 黔西县| 铁岭县| 荆门市| 渑池县| 马山县| 长沙县| 灵武市| 昌都县| 昌吉市| 瓮安县| 泰州市| 安新县| 大城县| 定陶县| 青神县| 临漳县| 烟台市| 通海县| 深水埗区| 崇阳县| 邵武市| 石渠县| 广南县| 阿拉善右旗| 镇安县| 交城县| 廉江市| 冷水江市| 探索| 灵台县| 甘德县| 平安县| 清水河县|