
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:
- In the VBA Editor, double-click on Module1 to open the code window.
- 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
- Switch back to Excel, clear all formatting on the data and run the macro. The result is the same as with the first test.
- Next, select all the lines after .HorizontalAlignment = xlCenter. Press Del:
Figure 1.18 – Selected code to be deleted
- 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.
- Finally, change the cell reference in the last line from A1 to G2:
Figure 1.19 – Cell reference to be changed
- 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.