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

notes7

notes

Uploaded by

Dilip Paliwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

notes7

notes

Uploaded by

Dilip Paliwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CHEN 3600 – Computer-Aided Chemical Engineering

Chemical Engineering Department Notes 7


EWE: “Engineering With Excel” Larsen Page 1

7. Using Macros in Excel.

Introduction

Before becoming familiar with VBA (Visual Basic for Applications) we will
focus on a related “capability” of Microsoft Office Products to record and
replay user-entered keystrokes and other input device information (mouse
movements, clicks, etc).

A “macro” refers to an “abbreviation”, that is, something that refers to


something else. The postal abbreviation OH represents OHIO and Cntl-C is
an “abbreviation” for “Edit/Copy”. We are very used to pressing “icons” on
toolbars and having the expected actions take place and these are nothing
more than “visual macros” (for example, pressing the “File Save” or “Print”
icons).

One of the main advantages of macros is that they can “flawlessly replay”
complex sequences of keystrokes (thus saving us a lot of time and effort).
One of the major disadvantages of macros is that they can “mindlessly and
swiftly replay” a complex sequence of keystrokes that should never have
been applied to the task at hand. Thus, macros are “double edge swords”
with both advantages and disadvantages.

A similar example of this might be to develop a macro to build the


“boilerplate” (template) of identification information at the start of a new
spreadsheet. By assigning this macro to the keystroke “Cntl-Q” one could
get a fast start on a new assignment. On the other hand, if you were
working on some other part of the spreadsheet and accidently pressed “Cntl-
Q” it is possible you might overwrite dozens of cells of information and
formulas because you didn’t start running the macro from row/column A1.

The easiest way to create a macro in Excel is just to let Excel “listen in” on
what keys/etc you are pressing and store these to be later executed by a
single keystroke. These “saved keystrokes” can be viewed and edited later.

Another way to create a macro is to start from scratch using the VBA Editor.

The largest limitation of macros is that they cannot accept information “on
the fly” (that is, there is no “argument list” to pass information to the
macro). Hence, you can write a macro to “add three” to the cell
immediately to the left of the current cell, but you cannot write a macro to
add “some number” to that same cell.
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 2

Macros and Viruses

Macros (from unknown or untrusted sources) are potentially dangerous


(acting as a virus) and capable of damaging a computer and its information.
Previous versions of Excel were configured to run macros “automatically”
however, current versions provide four levels of security to limit the dangers
macros represent.

Security:

• Very High – Only macros in installed in trusted locations (folders) are


allowed to run (you must maintain a list of the trusted locations)
• High – Only macros “digitally signed” by trusted sources are allowed to
run (you must maintain a list of trusted sources)
• Medium – Excel will prompt to run macros not from trusted sources.
• Low – All macros allowed to run without warning.

Recording Macros

Macro 1: Typing on the Diagonal – “Cntl n”

1. Start a new worksheet. Move the focus (selected cell) to C3.

2. Begin recording the macro (Tools/Macros/Record New Macro).

Fill in ONLY the “n”.


Note 1: Shift “N” and “n” will be different macros.
Note 2: You may name the macro (optional)

3. IMPORTANT: When you first start to record a macro, a “Stop


Recording” Toolbar should appear (having two buttons).
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 3

Note: The appearance of this toolbar varies with the version of Excel
being used.

The first button is pressed to STOP recording (don’t do that now).

The second button selected either “absolute mode” or “relative mode”.


This button functions similarly to the “Bold” button. When “down” it is
selected and the mode is “relative”. When “up” the button is
unselected and the mode is “absolute”.

Unfortunately, it is hard to see which mode is active because the icon


of the spreadsheet is very large compared to the size of the button.

Unselected Selected
Normal/Bold

Absolute/Relative

4. For this macro, we wish to have the recording mode be “absolute”.


This is the same issue in Excel when $-signs are used in cell formulas
(ie., $A$10 is an absolute address).

4a. IMPORTANT: For “unknown reasons” sometimes the “stop


recording” toolbar will fail to appear when you start recording a
new macro.
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 4

What has happened is that the “stop recording toolbar” has gotten
“unchecked” in the “View/Toolbars” menu. If this happens, you should
stop recording the current macro (delete it later) by selecting
“Tools/Macro/Stop Recording” and then selecting”

“View/Toolbars/Customize/[x] Stop Recording”

This will cause the “stop recording” toolbar to appear. It is suggested


that you drag the “stop recording” toolbar into the standard toolbars and
leave it permanently docked there (it will always be visible and in a
convenient location).

Note that the “stop recording” toolbar does not appear in the “toolbar list”
unless you are actually recording a macro. It ALWAYS appears in the
“customize list”.

5. Follow these typing directions exactly

Move to A1 and enter “1”


Move to B2 and enter “2”
Move to C3 and enter “3”
Move to D4 and enter “4”
Move to E5 and enter “5”
Move to F6.

6. Press the stop recording button.


CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 5

Sub Macro4()
'
' Macro4 Macro
' Macro recorded 2/22/2005 by Tim Placek
'
' Keyboard Shortcut: Ctrl+n
'
Range("A1").Select
ActiveCell.FormulaR1C1 = "1"
Range("B2").Select
ActiveCell.FormulaR1C1 = "2"
Range("C3").Select
ActiveCell.FormulaR1C1 = "3"
Range("D4").Select
ActiveCell.FormulaR1C1 = "4"
Range("E5").Select
ActiveCell.FormulaR1C1 = "5"
Range("F6").Select
End Sub

7. Test your macro by going to a new sheet (Sheet2) and pressing


“Cntl-n”

Try the macro in several other places (move your cursor to different
locations before pressing “Cntl-n”. Notice that wherever you locate the
cursor, the data will be created in the locations we originally put the data
(A1-E5).

Let’s edit the macro to see what we recorded. Tools/Macro/Macros/Edit

Notice that we can change any of these items and our macro will be
appropriately edited. Hence, you can make mistakes and “fix them” or make
the macro do new things.

In this case, change the values to 0, 0, 0, 0, 0. Test your macro. You could
also change the addresses to A5, B4, C3, D2, E1. You could also type
additional lines to add more “typing” or delete some lines.

Relative Mode: This time, do the same thing EXCEPT when you start the
recording, make sure “relative” mode is selected.
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 6

Start in cell C3 again.


Start to record your macro.
Name this macro “Cntl-p”
Switch to relative mode.
Do the same typing
End the macro.

Sub Macro5()
'
' Macro5 Macro
' Macro recorded 2/22/2005 by Tim Placek
'
' Keyboard Shortcut: Ctrl+p
'
ActiveCell.Offset(-2, -2).Range("A1").Select
ActiveCell.FormulaR1C1 = "1"
ActiveCell.Offset(1, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "2"
ActiveCell.Offset(1, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "3"
ActiveCell.Offset(1, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "4"
ActiveCell.Offset(1, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "5"
ActiveCell.Offset(1, 1).Range("A1").Select
End Sub

Test your macro as before but this time CAREFULLY.

Return to C3 and try your macro.


Go to E5 and try your macro.
Got to A1 and try your macro.

Notice that the latter case produces an error since the macro instructs the
computer to go to a position that doesn’t exist.
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 7

Macro 2: Making a Boilerplate (Name Template)

CLOSE your current workbook.


Start a new workbook.
Make the current cell be A1.

1. Make sure the following are selected:


• regular (NOT BOLD)
• Arial
• 10 point font size

2. Begin recording the macro (Tools/Macros/Record New Macro).

IMPORTANT: For this example, use the RELATIVE MODE.

3. Type your name and other information (similar to below)

Timothy D. Placek
CHEN 3600 - Computer Aided Chemical Engineering
Fall 2005

4. Highlight cells A1:H3 and (1) change the background color to “tan” (2)
make the characters “bold” (3) change the font size to “12” and
change the font to “Verdana”.

5. Click the “STOP RECORDING” button.

Timothy D. Placek
CHEN 3600 - Computer-Aided Chemical Engineering
Fall 2004
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 8

6. Test your macro by going to a new sheet (Sheet2) and pressing


“Cntl-n”

Try the macro in several other places. Notice that wherever you locate the
cursor, the data will be placed in that location (this is a relative reference).
If this doesn’t work, you did not get the relative/absolute mode setting
correct.
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 9

Let’s edit the macro to see what we recorded. Tools/Macro/Macros/Edit


“selected macro”

Sub ProgrammerName()
'
' ProgrammerName Macro
' Macro recorded 9/21/2004 by Tim Placek
'
' Keyboard Shortcut: Ctrl+n
'
ActiveCell.Select
ActiveCell.FormulaR1C1 = "Timothy D. Placek"
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = "CHEN 3600 - Computer-Aided Chemical Engineering"
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = "Fall 2004"
ActiveCell.Offset(-2, 0).Range("A1:H3").Select
Selection.Font.Bold = True
With Selection.Font
.Name = "Arial"
.Size = 12
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
End With
With Selection.Font
.Name = "Verdana"
.Size = 12
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
End With
With Selection.Interior
.ColorIndex = 40
.Pattern = xlSolid
End With
End Sub

Notice that we can change any of these items and our macro will be
appropriately edited. Hence, you can make mistakes and “fix them” or make
the macro do new things.
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 10

Macro 4: Operating On A Cell’s Value

In this macro we will enter a number in a cell based on the contents of the
cell immediately to the left of the cell, namely, we will multiply the value by
10.

1. Start on a new “Sheet”. Type the number “123.456” in cell D4.

2. Locate the cursor in cell E4.

3. Start recording a macro (Cntl-m)

4. Type the following in E4: =D4/10

5. Use the cursor keys to move the cursor to the cell just to the right of
E4 (namely F4).

6. Stop the recording.

7. Repeated pressing Cntl-m should cause the adjacent cells to contain


the desired values.

0.12345 0.01234 0.00123 0.00012


123.456 12.3456 1.23456 6 6 5 3 1.23E-05
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 11

Sub MultiplyByN()
'
' MultiplyByN Macro
' Macro recorded 9/21/2004 by Tim Placek
'
' Keyboard Shortcut: Ctrl+m
'
ActiveCell.Select
ActiveCell.FormulaR1C1 = "=RC[-1]/10"
ActiveCell.Offset(0, 1).Range("A1").Select
End Sub

Let’s alter the macro to take the value stored in A1 and use it in place of
“10”. Notice that the value in A1 is refered to by the general notation R1C1.
We could have gotten this same result if when we were recording the macro
we pressed the F4 key after pointing to the cell A1.

Notice that the numbers are getting bigger now because we have A1=0.1
(dividing by 0.1)!

Sub MultiplyByN()
'
' Multiply Macro
' Macro recorded 9/21/2004 by Tim Placek
'
' Keyboard Shortcut: Ctrl+m
'
ActiveCell.FormulaR1C1 = "=RC[-1]/R1C1"
ActiveCell.Offset(0, 1).Range("A1").Select
End Sub

Programmed Macros (VBA)

In this section we consider writing macros “from scratch” (that is, by


creating them with the VBA Editor rather than recording them).

Macros are stored in Modules in a fashion similar to functions. The main


difference is that macros perform an action (do something) rather than
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 12

return a value (calculate something). Also, macros do not have


“arguments”. Functions that do not return a value are called
“subprograms”.

Let’s begin by writing a macro that makes the background color of the cells
in the range A1:D6 “yellow”.

Macro 5: Yellow Range

Start a new worksheet with the “current cell” being A1.

1. Add a new subprogram called “yellowRange” to Module1. If you do


not have other files open, you should need to Insert a Module before
you start the subprogram (Insert/Module from the VBA editor “Insert”
menu).

Public Sub yellowRange()


Range("A1:D6").Interior.ColorIndex = 6
End Sub

2. Return to the worksheet and open the Tools/Macro/Macros menu.

We can run the macro (without a hotkey) by pressing “Run” …


CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 13

… or we can select the “Options…” menu and assign the macro to a key
(Cntl-u for example).

In this example, ColorIndex is a predefined set of colors numbered 1-56

ColorName ColorIndex RGB Values


Black 1 0,0,0
White 2 255,255,255
Red 3 255,0,0
Green 4 0,255,0
Blue 5 0,0,255
Yellow 6 255,255,0
Magneta 7 255,0,255
Cyan 8 0,255,255
(more) 9-56

2. We can also choose colors based on their RGB values directly.

Change your macro to the following:

Public Sub yellowRange()


Range("A1:D6").Interior.Color = RGB(127, 63, 0)
‘ This is some kind of brown color
End Sub
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 14

3. We can also “select” (leave highlighted) the range of cells by adding


the following:

Public Sub yellowRange()


Range("A1:D6").Interior.Color = RGB(127, 63, 0)
Range("A1:D6").Select
End Sub

4. In order to operate on the cells WE have selected (instead of knowing


which cells are in our range beforehand, use the following:

Public Sub yellowRange()


Range(ActiveWindow.RangeSelection.Address).Interior.ColorIndex = 4
End Sub

Make sure you have some cells selected before you run the macro again.
You should make the cells “Green” by this macro.

5. In order to put a value in the selected cells use the following:

Public Sub yellowRange()


Range(ActiveWindow.RangeSelection.Address).Interior.ColorIndex = 4
Range(ActiveWindow.RangeSelection.Address).Value = "CHEN3600"
Range(ActiveWindow.RangeSelection.Address).Font.Size = 6
Range(ActiveWindow.RangeSelection.Address).Font.Color = 1
Range(ActiveWindow.RangeSelection.Address).Font.Bold = True
End Sub

This will put the characters “CHEN3600” in green cells in a very small red
font with bold turned on.
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 15

6. In order to read a value out of a cell and put it in others, use the
following:

Public Sub yellowRange()


Range(ActiveWindow.RangeSelection.Address).Value = Cells(2, 4).Value
' Cells(2, 4) refers to "D2"
End Sub

7. In order to operate on values in a cell, it is easier to assign them to


“local variable” and then perform the calculations and assignment.

Public Sub yellowRange()


Dim n1 As Single
Dim n2 As Single
Dim n3 As Single
n1 = Cells(2, 4).Value ' This is D2
n2 = Cells(2, 5).Value ' This is E2
n3 = n1 + n2 ' Sum the two values
Range(ActiveWindow.RangeSelection.Address).Value = n3
End Sub

8. In this example, we read the value from A1 and write variations of it in


A2, A3, and A4.

Public Sub yellowRange()


Dim n1 As Single
n1 = Cells(1, 1).Value ' This is A1
Cells(2, 1).Value = n1
Cells(3, 1).Value = 2 * n1
Cells(4, 1).Value = 3 * n1
End Sub
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 16

Section 7.4.7 (Common Macro Commands) provides an introduction to other


useful elements of the VBA language which can be easily employed in writing
macros.

Some of these elements are:

• Changing the value in the active cell


• Changing properties of the active cell
o Border Color
o Border Linestyle
o Border Weight
o Font Name
o Font Color
o Font Size
o Font Italic/Bold/Underline/Subscript/Superscript
o Interior Color
o Interior Pattern
o Interior Pattern Color
• Changing the selected cell
• Selecting a range of cells
• Changing the values in a range of cells
• Changing the properties of a range of cells

We will explore many of these issues again when we formally consider VBA
programming in the next chapter.

Questions

In order to assess if you have understood the basic concepts discussed in


the text and these lecture notes, answer the following questions.

1. What is the difference between an ActiveCell and Select?

2. Suppose the cell A4 is currently highlighted in the worksheet. What


code would you cause the highlight to move to cell B5? Use “relative”
offset methods.

3. If you carry out question (2) which cell is the ActiveCell?

4. What code should be written to put the characters “hello” in cell B5


(assuming you have performed question (2)?
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 17

5. What code should be written to save the value of the contents of cell
C8 to the variable x? Use “absolute methods”.

6. What code should be written to save the value of the contents of cell
C8 to the variable y if the currently selected cell is D8? Use “relative
methods”.

7. What code should be written to put the sum of “x” and “y” into cell F9?
“Use absolute methods”

Answers

DO NOT READ THE ANSWERS UNTIL YOU HAVE ANSWERED THE


QUESTIONS!!
CHEN 3600 – Computer-Aided Chemical Engineering
Chemical Engineering Department Notes 7
EWE: “Engineering With Excel” Larsen Page 18

Answers

1. The ActiveCell is an object with various properties. Some of those


properties are (a) the value in the cell, (b) the formula in the cell, (c)
the interior color of the cell, (d) the font used in the cell, (e) the size of
the font used in the cell, etc. “Selected” is also a property of a cell and
when a cell is selected there is a “selection highlight” shown around
the cell. Therefore, in order to change which cell is “active” one
“selects” it using the .Select property.

2. ActiveCell.Offset(1, 0).Range("A1").Select

or

ActiveCell.Offset(1, 0).Select

3. B5 is now active (as indicated by the highlight)

4. ActiveCell.Value = "hello"

5. x = Cells(8,3).Value

6. y = ActiveCell.Offset(0,-1).Value

7. Cells(9,6).Value = x+y

You might also like