0% found this document useful (0 votes)
5 views

macro 2

This document provides a comprehensive guide on creating and using macros in Excel using VBA, including enabling the Developer tab, adding command buttons, and recording macros. It explains how to swap values, run code from modules, and utilize the Macro Recorder for automating tasks. Additionally, it covers the differences between absolute and relative references, the FormulaR1C1 style, and how to add macros to the Quick Access Toolbar, along with security settings for enabling macros.

Uploaded by

V-Tech Community
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

macro 2

This document provides a comprehensive guide on creating and using macros in Excel using VBA, including enabling the Developer tab, adding command buttons, and recording macros. It explains how to swap values, run code from modules, and utilize the Macro Recorder for automating tasks. Additionally, it covers the differences between absolute and relative references, the FormulaR1C1 style, and how to add macros to the Quick Access Toolbar, along with security settings for enabling macros.

Uploaded by

V-Tech Community
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Create a Macro in Excel

With Excel VBA you can automate tasks in Excel by writing so-called macros. In this
chapter, learn how to create a simple macro which will be executed after clicking on a
command button. First, turn on the Developer tab.

Developer Tab

To turn on the Developer tab, execute the following steps.

1. Right click anywhere on the ribbon, and then click Customize the Ribbon.

2. Under Customize the Ribbon, on the right side of the dialog box, select Main tabs (if
necessary).

3. Check the Developer check box.


4. Click OK.

5. You can find the Developer tab next to the View tab.

Command Button

To place a command button on your worksheet, execute the following steps.

1. On the Developer tab, click Insert.

2. In the ActiveX Controls group, click Command Button.


3. Drag a command button on your worksheet.

Assign a Macro

To assign a macro (one or more code lines) to the command button, execute the following
steps.

1. Right click CommandButton1 (make sure Design Mode is selected).

2. Click View Code.


The Visual Basic Editor appears.

3. Place your cursor between Private Sub CommandButton1_Click() and End Sub.

4. Add the code line shown below.


Note: the window on the left with the names Sheet1 (Sheet1) and ThisWorkbook is called the
Project Explorer. If the Project Explorer is not visible, click View, Project Explorer. If the
Code window for Sheet1 is not visible, click Sheet1 (Sheet1). You can ignore the Option
Explicit statement for now.

5. Close the Visual Basic Editor.

6. Click the command button on the sheet (make sure Design Mode is deselected).

Result:

Congratulations. You've just created a macro in Excel!

Visual Basic Editor

To open the Visual Basic Editor, on the Developer tab, click Visual Basic.

The Visual Basic Editor appears.


Swap Values in Excel VBA

This example teaches you how to swap two values in Excel VBA. You will often need this
structure in more complicated programs as we will see later.

Situation:

Two values on your worksheet.

Place a command button on your worksheet and add the following code lines:

1. First, we declare a variable called temp of type Double.

Dim temp As Double

2. We initialize the variable temp with the value of cell A1.

temp = Range("A1").Value

3. Now we can safely write the value of cell B1 to cell A1 (we have stored the value of cell
A1 to temp so we will not lose it).

Range("A1").Value = Range("B1").Value
4. Finally, we write the value of cell A1 (written to temp) to cell B1.

Range("B1").Value = temp

5. Click the command button twice.

Result:

Run Code from a Module in Excel VBA

As a beginner to Excel VBA, you might find it difficult to decide where to put your VBA
code. The Create a Macro chapter illustrates how to run code by clicking on a command
button. This example teaches you how to run code from a module.

1. Open the Visual Basic Editor.

2. Click Insert, Module.


3. Create a procedure (macro) called Cyan.

Sub Cyan()

End Sub

Note: a procedure is either a sub or a function. Learn more about functions and subs here, if
you like.

4. The sub changes the background color of your worksheet to cyan. To achieve this, add the
following code line:

Cells.Interior.ColorIndex = 28

Note: instead of ColorIndex number 28 (cyan), you can use any ColorIndex number.

To run the procedure, execute the following steps.

5. Click Macros.
6. Select Cyan and click Run.

Result:
Note: code placed into a module is available to the whole workbook. That means you can
select Sheet2 or Sheet3 and change the background color of these sheets as well. The Add a
Macro to the Toolbar program illustrates how to make a macro available to all your
workbooks (Excel files). Remember, code placed on a sheet (assigned to a command button)
is only available for that particular sheet.

Macro Recorder in Excel

The Macro Recorder, a very useful tool included in Excel VBA, records every task you
perform with Excel. All you have to do is record a specific task once. Next, you can execute
the task over and over with the click of a button. The Macro Recorder is also a great help
when you don't know how to program a specific task in Excel VBA. Simply open the Visual
Basic Editor after recording the task to see how it can be programmed.

Record a Macro

1. On the Developer tab, click Record Macro.


2. Enter a name.

3. Select This Workbook from the drop-down list. As a result, the macro will only be
available in the current workbook.

Note: if you store your macro in Personal Macro Workbook, the macro will be available to all
your workbooks (Excel files). This is possible because Excel stores your macro in a hidden
workbook that opens automatically when Excel starts. If you store your macro in New
Workbook, the macro will only be available in a new workbook which Excel opens
automatically for you.

4. Click OK.

5. Right mouse click on the active cell (selected cell). Be sure not to select any other cell!
Next, click Format Cells.
6. Select Percentage.

7. Click OK.
8. Finally, click Stop Recording.

Congratulations. You've just recorded a macro with the Macro Recorder!

Run a Recorded Macro

Now we'll test the macro to see if it can change the number format to Percentage.

1. Enter some numbers between 0 and 1.

2. Select the numbers.

3. On the Developer tab, click Macros.


4. Click Run.

Result:
See the Macro

To take a look at the macro, open the Visual Basic Editor.

Note: the macro has been placed into a module called Module1. Code placed into a module is
available to the whole workbook. That means you can change the number format of cells on
other sheets as well. Remember, code placed on a sheet (assigned to a command button) is
only available for that particular sheet. You can ignore the Option Explicit statement for now.

Unfortunately, there are a lot of things you cannot do with the Macro Recorder. For example,
you cannot loop through a range of data with the Macro Recorder. Moreover, the Macro
Recorder uses a lot more code than is required, which can slow your process down.

Use Relative References in Excel VBA

By default, Excel records macros in absolute mode. However, sometimes it is useful to


record macros in relative mode. This program teaches you how to do this. If you don't know
how to record a macro, we highly recommend you to read this example first.
Recording in Absolute Mode

To record a macro in absolute mode, execute the following steps.

1. First, click Record Macro.

2. Next, select cell B3. Type Sales and press enter.

3. Type Production and press enter.

4. Type Logistics and press enter.

Result:

5. Click Stop Recording.

6. Empty Range("B3:B5").

7. Select any cell on the sheet and run the recorded macro.

Result:
A macro recorded in absolute mode always produces the same result.

Recording in Relative Mode

Wouldn't it be nice to place these words anywhere on the sheet automatically? Not just
Range("B3:B5"). This would make the macro much more flexible. Solution: record the macro
in relative mode.

1. Select "Use Relative References".

2. First, select any single cell (for example, cell B8).

3. Next, click Record Macro.

4. Type Sales and press enter.

5. Type Production and press enter.

6. Type Logistics and press enter.

Result:
7. Click Stop Recording.

8. Select any other cell (for example, cell D4) and run the recorded macro.

Result:

Excel places the words relative to the initial selected cell. That's why it's called recording in
relative mode.

FormulaR1C1 in Excel VBA

This example illustrates the difference between A1, R1C1 and R[1]C[1] style in Excel VBA.

1. Place a command button on your worksheet and add the following code line (A1 style):

Range("D4").Formula = "=B3*10"
Result:

2. Add the following code line (R1C1 style):

Range("D4").FormulaR1C1 = "=R3C2*10"

Result:

Explanation: cell D4 references cell B3 (row 3, column 2). This is an absolute reference ($
symbol in front of the row number and column letter).

3. Add the following code line (R[1]C[1] style):

Range("D4").FormulaR1C1 = "=R[-1]C[-2]*10"

Result:
Explanation: cell D4 references cell B3 (one row above and 2 columns to the left). This is a
relative reference. This code line gives the exact same result as the code line used at step 1.

4. Why learning about this? Because the Macro Recorder uses the FormulaR1C1 property
(R[1]C[1] style). The Macro Recorder creates the following code lines if you enter the
formula =B3*10 into cell D4.

Explanation: you can see that this is the exact same code line used at step 3.

Add a Macro to the Toolbar in Excel

If you use an Excel macro frequently, you can add it to the Quick Access Toolbar. This
way you can quickly access your macro. First, we record an empty macro.

1. On the Developer tab, click Record Macro.

2. Name the macro MyName. Choose to store the macro in Personal Macro Workbook. This
way the macro will be available to all your workbooks (Excel files). This is possible because
Excel stores your macro in a hidden workbook that opens automatically when Excel starts.
3. Click OK.

4. Click Stop Recording.

5. Open the Visual Basic Editor.

6. Create the macro:


This macro places your name in the Active Cell.

7. Close the Visual Basic Editor.

8. Now we can add this macro to the Quick Access Toolbar. Click the down arrow and click
More Commands.

9. Under Choose commands, select Macros.

10. Select the macro and click Add.


11. You can modify the button that will be added to the Quick Access Toolbar by clicking on
Modify. For example, choose a smiley.
12. Click OK twice.

13. You can now execute the macro. For example, select cell E2 and click on the smiley
button added to the Quick Access Toolbar.

Result:
14. When you close Excel, Excel asks you to save the changes you made to the Personal
Macro Workbook. Click Save to store this macro in a hidden workbook that opens
automatically when Excel starts. This way the macro will be available to all your workbooks
(Excel files).

Enable Macros in Excel

Enable macros in Excel when the message bar appears. Change your macro security settings
in the Trust Center. To create macros, turn on the Developer tab.

1. When the message bar appears, click Enable Content to enable macros.
Note: by clicking Enable Content, the Excel file becomes a trusted document. As a result, you
won't see the Security Warning again when you open this specific Excel file in the future.

2. To change your macro security settings, on the Developer tab, click Macro Security.

The Trust Center opens.

1. The first option disables all macros.


2. The second option always asks you to enable a macro. Use this security level if you are
downloading a lot of Excel files from the internet. Don't click Enable Content (see first
screenshot on this page) if you don't trust the owner of the Excel file.
3. The third option only allows macros with a digital signature to run, and asks you to enable
others.

4. The fourth option enables all macros. Use this security level if you are a beginner and
only typing your own macros at the moment. With this security level you don't have to enable
macros all the time.
5. If you're new to Excel VBA, let's create a simple macro.

You might also like