16 Macros

• Explanation of macros and their use.
• Activating Developer tab.
• Recording a macro with the macro recorder.
• Modify a macro.
• Create command button.
• Security settings.

You can automate a task that you have to perform regularly in Microsoft Excel with a macro. A macro consists of a series of commands and functions that are executed in succession by a single command or the press of a button.

A macro is therefore primarily intended to be used for frequently occurring actions or for complex actions. By using a macro, efficiency can be increased and the chance of errors can be reduced.

Simple macros consisting of a number of actions performed in succession can be recorded with the built-in macro recorder. Complex macros are programmed in the VBA programming language. Only simple macros are discussed here, you do not need any programming knowledge for this.

The language in which the Excel macros are written is Visual Basic for Applications (VBA). The commands and functions of the macro are stored in a Visual Basic module. And with the Visual Basic editor, you can edit macros, copy macros from one module to another, copy macros between different workbooks, and rename modules and macros.

o be able to record, edit and execute macros, the tab Developers must be made visible.

A number of Excel functions, including those for Macros and VBA, are located under the Developers tab. This tab is not shown by default when Excel is installed and will therefore have to be made visible first. This is a one-time action.

First check whether the tab Developers is present on the ribbon. If so, you can skip this task.

1. Choose File > Options > Customize Ribbon.
1. Select under Main Tabs Developer and click OK.

The tab Developers should now be visible on the ribbon (see figure 16.1).

16.2 Recording macros

Simple macros can be created by recording the operations with the built-in macro recorder. After starting the recorder, all actions are recorded and converted into VBA code in the background. This continues until the recorder is stopped.

In order to get a properly working macro, it is important to first perform the actions to be performed without recording and write them down in order. You can then use this script to record the actions with the macro recorder.

The button with which you can start recording macros is on the Tab Developers in the group Code, see figure 16.1.

When this button is clicked to start recording a macro, a dialog box first appears in which a number of properties of the macro can be entered.

Macro name

Each macro must have a name. To do this, Excel fills in the default text “Macro” followed by a digit. You can change this name by typing a different name.

The first character of the macro name has to be a letter. After that, you can use other characters such as letters, numbers, or underscore. Spaces are not allowed in a macro name. Always give meaningful names showing what the macro is going to do. The underscore can be used as a separator between words.

Shortcut key

Macros can be executed through the menu, but this can also be done using keyboard shortcuts. These are shortcuts with the CTRL key combined with a letter key. If you want to assign a keyboard shortcut to the macro then you can enter the letter in the box. Putting for example the letter A in the box, then the key combination CTRL-A is the shortcut that allows you to start the macro.

It is not required to assign a keyboard shortcut to a macro, but this can be very useful for frequently used macros.

Store macro in

The locations where the macro can be stored are:

• This Workbook
• New Workbook
• Personal Macro Workbook

It is important to think thoroughly about it. If the macro is to be used only in the active workbook, choose This Workbook. Should the macro be used in other workbooks, so it is always available, then the Personal Macro Workbook is the best choice. The option New workbook is actually never used.

You should always specify the storage place. The default value is This Workbook.

Description

It is recommended that you give a brief description of what the macro does. When you create the macro you know it, but after a while, you may forget. It is not mandatory to specify a description.

All made choices can always be changed at a later stage.

Information need

Create a macro that should format the text in the selected cell with the font Comic Sans MS, bold, italic, 16 pt, and red. The column width must be adjusted to the width of the text in the cell. The name of the macro should be CellFormat.

Record macro

1. Start with an empty worksheet and enter a text in a cell.

2. Select the cell that contains the text.

3. Choose Developer tab > Record Macro (group Code).

4. Enter in the dialog box the name and a description of the macro.

1. Click OK.

2. Perform the following actions on the selected cell Right mouse click > Format Cells > tab Font and make the following settings:

• Font: Comic Sans MS
• Font style: Bold Italic
• Size: 16
• Color: Red
3. Choose tab tab Home > Format (group Cells) > Autofit Column Width.

4. Choose Developer tab > Stop Recording (group Code).

Now the macro can be tested for a correct operation.

Testing macro

1. Enter a text in another cell and select this cell.

2. Choose tab Developers > Macros (Program code group).

3. Select macro Cell Format and click Run.

1. Verify that the cell is correctly formatted.

2. Save the workbook as Excel Macro Workbook (*.xslm) with the name Cell Format.xlsm.

Wanneer je een werkmap met macro’s wilt opslaan, dan probeert Excel deze standaard op te slaan als een Excel-werkmap met de extensie .xlsx. Echter in dit formaat kunnen geen macro’s worden opgeslagen. Je moet dit zelf wijzigen in een Excel-werkmap met macro’s met de extensie .xlsm.

When you want to save a workbook with macros, Excel suggests to save it as an Excel workbook with the extension *.xlsx. However, in this format, no macros can be stored. You should change this yourself in an Excel workbook with macros with the extension *.xlsm.

To perform this task, it is necessary that the macro CellFormat in 16.3 is created.

A macro can be changed without recording the macro again. Both the options of the macro as the program code can be viewed and modified.

Information need

Make the following changes to the CellFormat macro:

• Assign the shortcut key “Control t”.
• Change the font size to 18 pt.
1. If necessary, open the CellFormat.xlsm file.

2. Choose Developer tab > Macros (group Code).

You now get the dialog box with available macros again, see figure 16.6

1. Select macro CellFormat and then Options.
1. Enter the letter t in the box for the shortcut key and change in the description 16pt in 18pt. Then click OK.

2. Choose now Edit.

A new Microsoft Visual Basic window will now appear with the program code of the macro in the code screen. In this code you will find 16 for the text size on two places:

• Format cell in Comic Sans, 16pt, bold, italic and red
• .Size = 16
1. Change it to 18 in both places.

2. Close the Microsoft Visual Basic window with the close button in the upper right corner.

3. Test the macro on a cell with text using the keyboard shortcut CTRL t.

16.5 Task: Creating a Command Button

You can run a macro in one of the following ways:

• Via the menu Developers tab > Macros > select macro > Run, see 16.3.
• Via a hotkey when one is assigned to the macro, see 16.4
• Via a command button for the macro.

This task creates a command button on the worksheet for the previously created macro Cell Format.

1. If necessary, open the CellFormat.xlsm file.

2. Choose Developer tab > Insert (group Controls).

3. Click on control [Button (Form Control)

The cursor will change to a +. With this cursor, you can draw a rectangle in the worksheet for the button.

1. Click the left mouse button and draw a rectangle with the desired dimensions for the button somewhere in the worksheet. Then release the left mouse button. The Assign macro dialog box then appears.
1. Select the macro CellFormat and click OK.

The drawn rectangle will turn into a button with a text like Button 1.

1. Select the text on the button and change it to a more appropriate text, for example, Cell format.
1. Deselect the button by clicking anywhere in the worksheet.

2. Test the macro via the command button on a cell with some text.

16.6 Macro Security

An overview of the security settings and how to change it.

Change settings

If you want to view or change the security settings for macros, then you need to click on Developer tab > Macro Security (group Code).

The dialog box Trust Center appears.

Table 16.1: Overview of Macro Settings.
Setting Explanation
Disable all macros without notification Choose this option if you don’t trust macros. All macros in documents are disabled, as well as the security alerts about macros. Documents that contain unsigned macros that you do trust can be saved in a trusted location. Documents in trusted locations are executed without control by the security system.
Disable all macros with notification This is the default setting. Choose this option when you want to disable macros, but want to receive security alerts if macros are present. This way you can choose if you want to enable each macro.
Disable all macros except digitally signed macros The creator of a macro can digitally sign it. When you consider this as a trusted authority then the macro will be executed without warnings. All unsigned macros will be disabled without notification.
Enable all macros Choose this option when you want to run all macros. This option is not recommended because the computer is then vulnerable for malicious macros.

16.7 Tips

Relative References

Recorded macros will use absolute cell references by default. This means that the exact locations of cells, rows, and columns in the program code of the macro will be used. The macro works then always at the same addresses.

When you want to use relative references in the macro you need to click on the button Use Relative References.

This setting remains active until you undo the setting by clicking on this button again.

Deleting macros

Macros can be deleted by Developer tab > Macros (group Code) > Select macro > Delete.

16.8 Exercises

macr001 - Background color

Record a macro that gives the active cell a gray background color.

An example of a solution.

Sub Background_Gray()
'
' Lightgray background for active cell
'
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
End With
End Sub

macr002 - Percentage formatting

Record a macro with the name PercentageFormat that is formatting a numeric value as a percentage with 1 decimal and also centers the content in the cell.

An example of a solution.

Sub PercentageFormat()
'
' Numeric value formatted as percentage with 1 dec. and horizontally centered
'
Selection.NumberFormat = "0.0%"
With Selection
.HorizontalAlignment = xlCenter
End With
End Sub

macr003 - Formatting cell A1

Record a macro that performs the following:

• Height of row 1 is 18
• Width of column 1 is 3
• Font of text in cell A1 is Tahoma 14, bold, blue color

An example of a solution.

Sub FormatA1()
'
' exercise macr003
'
Rows("1:1").Select
Selection.RowHeight = 18
Columns("A:A").Select
Selection.ColumnWidth = 3
Range("A1").Select
With Selection.Font
.Name = "Tahoma"
.Size = 14
.Bold = True
.Color = -4165632
End With
End Sub

macr004 - Printing gridlines

Create a macro that ensures that the grid lines will be printed at printing.

You can find this property at the tab Page Layout > Page Setup > tab Sheet.

An example of a solution.

Sub Print_Gridlines()
'
' exercise macr004
'
With ActiveSheet.PageSetup
.PrintGridlines = True
End With
End Sub