Excel 1
Excel 1
20-Oct-10
1
What you will take away
How to record a macro
How to edit a macro
Understanding VBA
And of course “when to make a macro?”
2
Recording the macros
Excel macro recorder – best teacher and assistant
Record macro in 2003:
tools > macros > record new macro
Record macro in 2007:
developer > macro > record macro
Run macro in 2003:
tools > macros > run
Run macro in 2007:
developer > macro > run
Use relative reference to print the output where the cursor is
pointing
3
Modifying a macro
Tools > macro > macros > edit
Code can be edited, deleted or added to make the output
better
Macro recorder record all your steps, it record even those
steps that were undone or were wrong
Excel comes with an excellent help file and you should refer it if you are in trouble
4
Introduction to VBA
VBA – the language Excel understands
Alt+F11 to open VBE
If you delete the workbook, the procedures are deleted too
Remember that once the macro is run you cannot undo the
operation
To check the code press F5
5
Code window
To write and to test the VBA sentences
Type the code and click on run / press F5
Defining variables
dim x as integer
dim x as variant
dim x as string
6
Code window
Some commands
range(“a1”).select
range(“a1”).value = 1/8
First program
„the program prints “hello world” in cell A1 of Sheet1
sub prog1()
sheets("sheet1").select „selecting the sheet
range(“a1”).select „selecting the cell
ActiveCell = “hello world” „printing the statement
end sub
7
Working with workbook
Save a workbook > thisworkbook.save
Exit a workbook > thisworkbook.close
The errors will be pointed out to you by the compiler during run. Don’t worry if you see errors they are common
in nature and debugging them is easy as well.
8
Ranges and cells
Select a cell
cells(11,31).select
range(“ae11”).select
Select all continuous cells
range(“a1:g5”).select
Select non- continuous cells
range(“a1:a5,d1,z200”).select
Be smart and avoid writing codes. You can always record a macro!!!
9
Offset
Move one cell down from b2 to b3
Range(“b2”).offset(1,0).select
Move one cell right from b2 to c2
Range(“b2”).offset(0,1).select
Move one cell up from b2 to b1
Range(“b2”).offset(-1,0).select
Move one cell left from b2 to b3
Range(“b2”).offset(0,-1).select
10
Open for discussion
When to make a macro?
What do you expect to learn in the next session?
Never write macros for filter, conditional formatting and cell formatting. Record a macro or do
it manually. It saves time!!!
11