Vous êtes sur la page 1sur 24

Page | 1 10/12/2014 3:53 PM

Macros & Programming


ACCT 628 Sanders
Steps for Developing Macros
1. Understand read the problem all the way through to make sure you understand the big picture
2. Plan
a. Read the problem again and identify tools and programming concepts
b. Highlight key phrases
c. Answer pre-pseudocode questions
d. Write pseudocode
3. Build
a. Identify which lines can be recorded and which ones are typed (write R & T)
b. Identify if you should record in relative or absolute reference
c. Practice recorded code
d. Record code
e. Open code
f. Add Option Explicit
g. Separate out code with spaces and add comments for each section
h. Step through code using F8 to see what it does and may add comments (make sure you
can see Excel in the back and code in the front)
i. Type in code needed
j. Look for hardcoded values to replace with variables
k. This could be done in small steps for each part of the project
4. Test
a. Test each step as you build it
b. Put in values that test all conditions
c. Use debugger to step through code and watch what it does
5. Use
a. Reread original problem to make sure it meets all the requirements
b. Think about the characteristics of a good model
i. Accuracy be sure to test for all conditions
ii. Simplicity record fewest key strokes possible
iii. Ease of Use should you add buttons or instructions
iv. Ease of Communication format of results and comments in code
v. Adaptability replace hardcoded values with variables
- use input boxes to allow user to enter values

Page | 2 10/12/2014 3:53 PM

Macro Basics
The following excerpts from the text and lectures are key points and definitions that should help you
understand and work with macros:
1. You create macros to automate frequently performed Excel tasks.
2. A macro is a set of instructions that performs tasks in the order you specify. It starts at the top of
the macro and processes each line in order until it reaches the end.
3. Items in the code window that appear in blue are keywords, which are words Excel recognizes as
part of the VBA programming language.
4. Comments, which are notes explaining the code, appear in green. Comments are simply there
for humans to read. An apostrophe () indicates that anything following it on that line is a
comment and the computer ignores it.
5. To create a macro, you record the series of actions or write the instructions in a special
programming language called Visual Basic for Applications (VBA).
6. Because the sequence of actions is important, you need to plan the macro carefully before you
record it.
7. As you record the macro, Excel automatically translates each action into program code you can
later view and modify. The code appears in the same order in which you recorded the steps.
8. Using the recorder to create your macros assures that the basic structure is correct and it is
saved in the correct location. It also lets you add a short-cut key when it is created.
9. You can edit the macro code directly using the Visual Basic Editor, a program that lets you
display and edit your macro code.
10. You can copy and paste code from one macro and/or module to another.
11. Actions that you can perform in Excel may be recorded.
12. Programming concepts, which extend the capabilities of Excel, must be typed.
13. The three programming concepts we will learn are:
a. Conditional (IF) statements performs different code based on a condition
b. Variables runs the same code using different values
c. Loops repeats the same code multiple times
14. Input boxes allow the user to enter information while the program is running. They also must be
typed.
15. Every element of Excel is considered an object (ex: a cell or range)
16. A property is an attribute of an object that defines one of the objects characteristics or an aspect
of its behavior. When you open and make selections in a dialog box while you are recording a
macro, Excel includes all of the property settings in the code. If you did not change one then the
default is listed.
17. You can change multiple properties for an object using the With/End With structure.
18. By default Excel records code in an absolute reference (Range(B3)). You can change it to a
relative reference (Activecell.Offset(0,1)) by selecting the Use Relative References button on the
Developer or View Ribbon.
19. If you record code you may see an additional reference to Range(A1) or .Value. Those are just
default values and do not need to be typed.


Page | 3 10/12/2014 3:53 PM

20. You can populate a cell without actually selecting it but you cannot populate and select a cell in
the same statement.
21. Formatting commands affect what is displayed in a cell NOT what is stored in a variable.
22. Realize that variables exist in VBA while your program is running. They do not exist on the Excel
spreadsheet. If you insert a formula that has a variable name for one of the arguments it will not
work. That is why they have to be concatenated into the text string containing the formula.
23. Named ranges and tables can be used in VBA but have to be referenced as Range("name")
24. Absolute cell references in code do not change when you insert rows/columns in a spreadsheet.
You may use named ranges to assure the logical reference does not change.
25. When writing VBA, you must follow the formatting rules, or syntax, of the VBA programming
language exactly. A misspelled keyword or variable name causes a procedure to fail with a
syntax error.
26. You can change or assign a shortcut key to a macro by going to the Developer or View Ribbon
and selecting Macros-Selecting the macro and pressing Options.
27. If your shortcut key is not working check the module name. If you renamed the module change it
back to Modulex and it should start working again.
28. Modules that are saved within This Workbook are saved in the Excel file so any changes to the
macros are also saved when you save the workbook.
29. Be careful NOT to save the macro as a Personal Workbook Macro.
30. The Excel file should be saved as a Macro Enabled Workbook (xlsm). If you save it as a regular
.xlsx file it will not save the macro.
31. To open the VBA Editor, you may simply press Alt+F11.
32. You cannot undo (ctrl+z) changes made by a macro. It is always a good idea to have a backup
of the data before running one.
33. It is also a good idea to have a copy of code that you know works before making any major
changes to it.

Common VBA Statements to Type:

Application.ScreenUpdate = False turns off screen display

ActiveSheet.Name = text renames the active worksheet

Option Explicit forces you to declare your own variables

DIM VariableName as DataType declares a variable

Anything = something populates an object

ActiveCell.Offset(1,0).Select moves down one row

Page | 4 10/12/2014 3:53 PM

Macro Demo Intro code from Excel file

Page | 5 10/12/2014 3:53 PM



Page | 6 10/12/2014 3:53 PM

Variables
A variable is simply a named storage location in your computers memory a holding place so you can
save information to use later. Variables allow the same code to be run using different values. It is a good
alternative to hard-coding values in code. You assign a value to a variable by using the equal sign (for
example, InterestRate = 0.069). The values assigned to variables are only saved temporarily though.
When a program stops, the variables and the values they contain are gone.
There are 3 steps to working with variables in a programming environment.
1. Declare the variable (create a place in memory, give it a name and type of data to store)
DIM VariableName as DataType
2. Populate the variable (place a value in it)
VariableName = something
3. Reference the variable (use it within the program)
The following are rules for working with variables within VBA. Different programming languages may
have different specific rules but the concepts are the same.
Naming Conventions
It is good practice to make variable names as descriptive as possible but there also specific rules that
VBA requires:

You can use alphabetic characters, numbers, and some punctuation characters, but the first
character must be alphabetic.
VBA does not distinguish between case. To make variable names more readable, programmers
often use mixed case (Ex: InterestRate rather than interestrate)
You cannot use spaces or periods. To make variable names more readable, programmers often
use the underscore character (Ex: Interest_Rate).
Special type declaration characters (#, $, %, & or !) cannot be embedded in a variable name.
Variable names may comprise as many as 254 characters not a good idea though.
VBA has many reserved words which are words that you cannot use for variable or procedure
names (for example, Next). If you attempt to use one of these words, you will get an error
message.
Page | 7 10/12/2014 3:53 PM

Data Types
Date type refers to how data is stored in memory as integers, real numbers, strings, and so on.
Although VBA can take care of data typing automatically, it does so at a cost: slower execution and less
efficient use of memory. It is recommended to specifically state the data type needed.
Common Data Types Valid Values
Variant (default) Any value Data type changes based on current value
String Any Character as text
Object Any object reference (ex: worksheet, cell, etc.)
Boolean True or False
Integer Whole number between 32,768 and 32,767
Long Whole number between 2,147,483,648 and 2,147,483,647
Single +/- extremely large numbers with lots of decimal places
Double +/- even larger numbers with lots of decimal places
Currency +/- number in the trillions with 4 decimal places
Date January 1, 0100 to December 31, 9999
Default Declaration
By default if you use a word in a macro that VBA does not know, it creates a variable with that name and
a data type of variant. This can lead to three main problems:
1. VBA can select the wrong data type and cause unexpected results. If a telephone number is
entered as a text string (1234567890) but in the macro the user enters that same number
(1234567890) into a variable with a variant datatype, VBA will declare that value to be a long.
Then if the program compares those two values, they are not equal which may cause unexpected
results. 1234567890 not = 1234567890.
2. You can easily misspell a name and unintentionally create a new variable. Say that you use a
variable named CurrentRate. At some point in your routine, however, you insert the statement
CurentRate = .075. This misspelled variable name, which is very difficult to spot, will create and
populate a new variable instead of populating the existing one. This will not generate a syntax
error but will likely cause your routine to give incorrect results (a logic error).
3. Your programs run slower and are less efficient. The default data type, variant, causes VBA to
repeatedly perform time-consuming checks and reserve more memory than necessary. If VBA
knows the data type, it doesnt have to constantly monitor the values and it can reserve just
enough memory to store the data.
Note that when you use a variable that has been declared, VBA automatically capitalizes it as it appears
in the DIM statement. This may also help spot misspellings.
Page | 8 10/12/2014 3:53 PM

Forced Declaration
To force yourself to declare all the variables that you use, include the following as the first line of code
(above the first Sub) in your VBA module:
Option Explicit
This statement causes your program to stop whenever VBA encounters a variable name that has not
been declared. VBA issues a syntax error message, and you must declare the variable before you can
proceed.

Scope (optional)
A variables scope determines which modules and procedures the variable can be used in. A variables
scope can be any of the following:

Scope How a variable with this scope is declared
Local or Private (Single
procedure)
Include a Dim or Private statement within the
procedure.
Ex: Dim Counter as Integer
Modulewide (All procedures in
single module)
Include a Dim statement before the first procedure in a
module.
Ex: Dim Counter as Integer
Global or Public (All
procedures in all modules in
workbook)
Include a Public statement before the first procedure in
a module.
Ex: Public Counter as Integer

NOTE: For medium to large-scale workbook applications, it is recommended to avoid the use of global
variables because they increase the application overhead. In other words, they use more memory and
run slower because Excel has to maintain their values until the workbook is closed even if the application
no longer needs the value stored in the variable. One alternative to using global variables is to pass the
values to procedures using parameters or arguments. Another alternative is to store the value in a cell
and then reference the value by using the cell locations instead of a variable name. For smaller
applications, global variables can be used to simplify the procedures.

Page | 9 10/12/2014 3:53 PM

Loops
Controls repeated actions in a program. Use a loop instead of repeating the same code over and
over again.
If need to add or change code then only have to make the change one time.
Any executable statement is allowed within loop & can have multiple commands within a loop.
Three alternative loop structures -- For Next, Do While and Do Until (choose the version that is
most natural for the specific problem)
For Next Loop
If know the number of times the loop will be executed then use For-Next loop.
FOR counter = start to end NEXT counter
Repeats a block of statements a specific number of times.
FOR loops use a counter variable whose value is increased or decreased by a set value with
each repetition of the loop. (default is +1)
Can use a variable for the start and/or end values.
Action
The computer executes each statement in the body of the loop.
At the bottom, it increases (or decreases) the value of the counter based on the step (default is
+1).
If the value of the counter variable is less than or equal to the end value, it executes the
statements in the body of the loop again.
When the counter value is greater than the end value, it exits the loop and goes on to the next
statement after the loop.
Example
The following procedure places the numbers 1 through 4 in adjacent columns. The For statement
specifies the counter variable (i) and its start and end values (1 to 4). The Next statement
increments the counter variable by 1. Macro Demo ForNext.xlsm contains the following code.
Sub ForNextLoop()

'Makes cell A1 on Sheet2 the active cell
Sheets("Sheet2").Select
Range("A1").Select

Cells.ClearContents 'Deletes all the cells on the worksheet

'Goes through the loop 4 times and inserts the value of i into the selected cell
'Moves to the right i number of cells
For i = 1 To 4
ActiveCell.Value = i
ActiveCell.Offset(0, i).Select
Next i
End Sub

Page | 10 10/12/2014 3:53 PM

Psuedocode
When programmers plan the logic for a solution to a programming problem, they often use one of two
tools, flowcharts or pseudocode (pronounced "sue-dough-code"). A flowchart is a pictorial
representation of the logical steps it takes to solve a problem. Pseudocode is an English-like
representation of the same thing. Pseudo i s a prefix that means false, and to code a program means
to put it in a programming language; therefore pseudocode simply means "false code," or sentences
that appear to have been written in a computer programming language but don't necessarily follow all
the syntax rules of any specific language. Pseudocode is a communication tool that can be used to
bridge the gap between programmers and users when specifying program requirements. Using
pseudocode involves writing down the main steps you will use in a program.
Excerpts taken from A Guide to Programming Logic & Design by Joyce Farrell, Course Technology, 1999.

Pre-Pseudocode Questions
Sometimes it is helpful to identify the concepts that need to be performed first and then you can
assemble them into the right order in the pseudocode. These questions might help identify what
needs to be done.
Does it matter where you start?
Is there any data you need to get from the user? Inputboxes Variables
Does any value change each time you run it? Variables
Is there anything dependent upon a condition? If Statements
Is anything repetitive? Loops
o Do you know how many times it needs to be done?
Yes ForNext Loop
No DO Loop
Is there anything else that needs to be done? Titles, Calculations, etc.

Formatting Guidelines
Psuedocode can be written in many different formats but the following are some industry standards to aid
in the communication process:
Statements should be written in the same order that the commands will need to be executed.
Commands inside of conditional statements and loops should be indented to indicate what is
performed within those statements. This makes it easier to read and understand.
Show key words such as MOVE, WRITE, and PROMPT in a different color, font, or capitalized to
make them "stick out."
It should focus on the logic, not the specific programming syntax.
Variable names should be referenced consistently throughout the psuedocode.
End every IF with an ENDIF.
Begin every loop with a LOOP instruction; end every loop with ENDLOOP.
If you find yourself repeating the same logic over and over again, it should be structured into a
loop. The same logic should only be programmed one time.
Think of psuedocode as an outline of the program.

Page | 11 10/12/2014 3:53 PM

Macro Demo Project 1

The following pseudocode is the logic to enter and display the sales quota for each region along with
a message stating how well each region did.

DEFINE Variables: Period, Sales, i, UnderQuota, BonusPercent

PROMPT for Period
COPY Template to new Report
RENAME Report Sales for X where X is the Period entered
DISPLAY Period on Report

SELECT Bonus Sheet
COPY BonusPercent
SELECT Report


SELECT Northern Region as Starting Point
FOR i = 1 to 5
PROMPT for Sales
DISPLAY Sales on Report

IF Sales >= Quota * (1 + BonusPercent) THEN
DISPLAY Excellent! You receive a bonus.
ELSE
IF Sales > Quota THEN
DISPLAY Good Job!
ELSE
UnderQuota = Quota Sales
DISPLAY Work Harder! You are X cars under your quota.
where X is UnderQuota
END-IF
END IF

MOVE to Next Region
END-LOOP

ADD Totals for Quota
ADD Totals for Sales

Page | 12 10/12/2014 3:53 PM

Page | 13 10/12/2014 3:53 PM

Page | 14 10/12/2014 3:53 PM

Page | 15 10/12/2014 3:53 PM

Steps to debug a logic error
1. Guess what part of the code is not working
2. Set a breakpoint where you want to start stepping through the code
3. Guess what variable value or object might be causing the error
4. Add a watch for those variables and/or objects (if comparing good to include both)
5. Position windows so you can see the code, watch window and Excel
6. Run the code from the VB Editor
7. Use F8 to step through the code line by line while watching Excel and the watch window
8. Analyze what the code is actually doing by looking at where the cursor moves and monitoring the
values and data types of the variables in the watch window
Breakpoints
Breakpoints allow you to suspend execution at a specific statement in a procedure. For example, if your
code has a problem at the end you can run the code and have it pause at that point instead of pressing
F8 through the entire program.
To set a breakpoint
1. Position the insertion point anywhere in a line of the procedure where you want execution to halt.
2. Click next to the statement in the Margin Indicator Bar (if visible); or on the Debug menu, click
Toggle Breakpoint (F9), or use the toolbar shortcut.
3. The line with the breakpoint should be highlighted.
To clear a breakpoint
1. Position the insertion point anywhere on a line of the procedure containing the breakpoint.
2. Click next to the statement in the Margin Indicator Bar (if visible.) or from the Debug menu,
choose Toggle Breakpoint (F9).
3. The breakpoint is cleared and highlighting is removed.
Watch Expressions
A watch expression is an expression you define to be monitored in the Watch window. When your
application enters break mode, the watch expressions you selected appear in the Watch window where
you can observe their values as you step through the procedure. This allows you to see the values
change as you step through the code instead of moving the curser over the object to see the value.
To open the Watch Window select View-Watch Window.
To add a watch highlight the object and drag it down to the Watch Window.
Page | 16 10/12/2014 3:53 PM


Page | 17 10/12/2014 3:53 PM

Page | 18 10/12/2014 3:53 PM

Page | 19 10/12/2014 3:53 PM

Page | 20 10/12/2014 3:53 PM


Macr
o
Demo
Calcu
lation
s &
Dates




Page | 21 10/12/2014 3:53 PM


Page | 22 10/12/2014 3:53 PM

Page | 23 10/12/2014 3:53 PM

Page | 24 10/12/2014 3:53 PM

Vous aimerez peut-être aussi