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

Macro Basics

The document provides instructions on how to create and run macros in Excel VBA. It begins by explaining how to turn on the Developer tab and insert a command button. It then describes how to assign a macro to the button by adding code lines. Several examples of macros are provided, such as one that swaps the values in two cells and one that changes the background color. It also explains how to use the macro recorder to automate tasks and view the recorded code.

Uploaded by

Marimuthu Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Macro Basics

The document provides instructions on how to create and run macros in Excel VBA. It begins by explaining how to turn on the Developer tab and insert a command button. It then describes how to assign a macro to the button by adding code lines. Several examples of macros are provided, such as one that swaps the values in two cells and one that changes the background color. It also explains how to use the macro recorder to automate tasks and view the recorded code.

Uploaded by

Marimuthu Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Macro Basics

Wednesday, September 20, 2017 10:20 PM

Create a Macro
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.

Macro Page 1
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.

From <http://www.excel-easy.com/vba/create-a-macro.html>

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.

Macro Page 2
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, Sheet2 and Sheet3 is called the Project Explorer. If
the Project Explorer is not visible, click View, Project Explorer. To add the Code window for the first
sheet, click Sheet1 (Sheet1).
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.

Macro Page 3
Swap Values
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 two times.
Result:

Macro Page 4
Run Code from a Module
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.

Macro Page 5
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
Record a Macro | Run a Recorded Macro | See the Macro
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

Macro Page 6
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.
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.
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 an automatically new opened workbook.
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.

Macro Page 7
6. Select Percentage.

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

Macro Page 8
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.

Macro Page 9
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 select Sheet2 or Sheet3 and change the number format of
cells on these sheets as well. Remember, code placed on a sheet (assigned to a command button) is only
available for that particular sheet.

From <http://www.excel-easy.com/vba/examples/macro-recorder.html>

Macro Page 10
Use Relative References
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").

Macro Page 11
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
Macro Page 12
FormulaR1C1
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.

Macro Page 13
Add a Macro to the Toolbar
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 Stop Recording.

4. Open the Visual Basic Editor.


5. Create the macro:

Macro Page 14
This macro places your name in the Active Cell.
6. Now we can add this macro to the Quick Access Toolbar. Right click the Quick Access Toolbar and
select Customize Quick Access Toolbar.

7. Under Choose commands, select Macros.


8. Select the macro and click Add.

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

Macro Page 15
10. Click OK.
11. You can now execute the macro by clicking on the smiley button added to the Quick Access Toolbar.
Result:

12. 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).

From <http://www.excel-easy.com/vba/examples/add-a-macro-to-the-toolbar.html>

Macro Security

Macro Page 16
To set up the macro security settings in Excel, execute the following steps.
1. On the Developer tab, click Macro Security.

2. Here you have four options. The first option will disable all macros. The second option will always ask
you to enable a macro. The third option will only allow macros with a digital signature to run, and ask
you to enable others. The fourth option will enable all macros.

Our advice is to use the second security level if you are downloading a lot of Excel files from the
internet. With this security level you can always disable the macro if you don't trust the owner of the
Excel file. Use the fourth 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.

From <http://www.excel-easy.com/vba/examples/macro-security.html>

Protect Macro
Just like you can password protect workbooks and worksheets, you can password protect a macro in
Excel from being viewed (and executed).
Place a command button on your worksheet and add the following code lines:
1. First, create a simple macro that you want to protect.
Range("A1").Value = "This is secret code"
2. Next, click Tools, VBAProject Properties.

Macro Page 17
3. On the Protection tab, check "Lock project for viewing" and enter a password twice.

4. Click OK.
5. Save, close and reopen the Excel file. Try to view the code.
The following dialog box will appear:

You can still execute the code by clicking on the command button but you cannot view or edit the code
anymore (unless you know the password). The password for the downloadable Excel file is "easy".
6. If you want to password protect the macro from being executed, add the following code lines:
Dim password As Variant
password = Application.InputBox("Enter Password", "Password Protected")

Select Case password


Case Is = False
'do nothing
Case Is = "easy"

Macro Page 18
Case Is = "easy"
Range("A1").Value = "This is secret code"
Case Else
MsgBox "Incorrect Password"
End Select
Result when you click the command button on the sheet:

Explanation: The macro uses the InputBox method of the Application object. If the users clicks Cancel,
this method returns False and nothing happens (InputBox disappears). Only when the user knows the
password ("easy" again), the secret code will be executed. If the entered password is incorrect, a
MsgBox is displayed. Note that the user cannot take a look at the password in the Visual Basic Editor
because the project is protected from being viewed.

From <http://www.excel-easy.com/vba/examples/protect-macro.html>

Macro Page 19

You might also like