MS Excel – Macros using VBA
By :- Amit Dhingra
Agenda
• Macro Security
• Recording a Macro
• Running a Macro
• Introduction to VBA
• Writing and debugging code in VBA
• Looping using VBA
CSC Proprietary 06/09/2004 Page: 2
Macro Security
• 4 types
• Low
• Medium
• High
• Very High
• Option to choose which macro to run available
under the Medium security level
CSC Proprietary 06/09/2004 Page: 3
Recording a Macro
CSC Proprietary 06/09/2004 Page: 4
Running a Macro
• Press “ALT + F8” for the list of Macros
• Press the Shortcut directly for the Macro
CSC Proprietary 06/09/2004 Page: 5
Exercise
A B C
S.No Name Marks
Record a macro that gives
1 Amit 56
2 Kamal 67
the following output
3 Namrata 68
4 Deepti 59
5 Yogesh 78
1. Cell D1=Average Marks
2. Cell E1=Total Students
3. Cell F1=Count of Students who have scored above 65
4. Cell D2 to D5 should have either “ABOVE” or “BELOW” based
upon the value in cells C2 to C5 as compared to the average in
D1.
CSC Proprietary 06/09/2004 Page: 6
Some more Macros
• Working with multiple sheets
• Working with multiple files
CSC Proprietary 06/09/2004 Page: 7
Exercise
• Create a Macro that gives
• The first 5 characters of “Asset Location” (Column F) in
Facility (Column G)
• Fetches the City (Column H) based upon Facility (Column
G) from the Facility Code sheet.
e.g.
CSC Proprietary 06/09/2004 Page: 8
Introduction to VBA
• Right Click on sheet name - > view code
• Press “ALT”+”F11”
• Write or Edit the code for macro in the modules
under project explorer
CSC Proprietary 06/09/2004 Page: 9
Writing Code in VBA
CSC Proprietary 06/09/2004 Page: 10
Conditional Statements
• If…. Then…..End if
• Select Case….. End Select
CSC Proprietary 06/09/2004 Page: 11
Exercise
• Display the Full Name as
• Last Name , First Name - If Last name is not blank
• First Name - If Last name is blank
For the following data:
SNo FirstName LastName Full Name
1 Amit Gupta ?
2 Deepak ?
3 Ajay Sharma ?
4 Payal Mehta ?
5 Deepak ?
CSC Proprietary 06/09/2004 Page: 12
Looping
• While……Wend
• Do……….Loop While
• For………Next
CSC Proprietary 06/09/2004 Page: 13
Exercise
• Display the sum of all the data of Column A in the
cell F1.
– Do not use the Sum Formula…. Use the While / Do or
For loop.
– The number of cells which have the data in Column A is
not fixed.
CSC Proprietary 06/09/2004 Page: 14
Thanks
Contact Details
Amit Dhingra
SH-103, A-91, Sector-2, Noida
0120-3064000 ext. 3648
Nortel Ext. 3648
CSC Proprietary 06/09/2004 Page: 15