Professional Documents
Culture Documents
VBA Macros
VBA Macros
VBA Macros
Automation in MS Excel
Overview
Macros
11 22
3
Menu Bar
Toolbar
Project
Explorer
Code
Properties
Window
Window
• Cannot start with a number (however a macro name can definitely contain a number, like Macro1 is
valid while 1Macro is invalid name)
• Cannot repeat
Sub MacroName()
….
….
….
(code comes here)
….
….
….
End Sub
For instance,
• MyPassword = “Password*01” (text value)
• Counter = 100 (non-fractional number)
• TaxAmt = 200.15 (fractional number)
• Insert a shape in Excel sheet -> Right click on shape -> Click on Assign Macro and select the code.
The code shall run when you click on the shape later
• Use shortcut key combination assigned to macro to run it. You may assign shortcut key while
recording a macro. Alternatively, for a written code, press Alt F8 -> Select the code -> Click on
Options -> Assign shortcut key
• Insert Form Control Button and assign macro to it, or use ActiveX Control Command Button to call
macro or write macro
Application.WorksheetFunction.ExcelFunction
For instance,
• Application.WorksheetFunction.RANDBETWEEN( )
• Application.WorksheetFunction.PROPER( )
• Application.WorksheetFunction.VLOOKUP( ) etc.
Syntax Example:
If Condition Then
Result
ElseIf Condition Then
Result
…
…
…
Else
Result - You may use multiple Elseif statements to check
End If for multiple conditions
- Note that ElseIf is a single word
Syntax:
Function FunctionName(Variables)
….
….
(code comes here)
….
….
End Function
Loop Categories
Example:
For Counter = 1 To N
…
…
… (statements)
…
…
Next
Example:
Do Until Condition
…
…
… (statements)
…
…
Loop
For instance,
✓ Each Sheet in a collection of Sheets in Workbook → For Each WkSht In ActiveWorkbook.Worksheets
✓ Each Cell in a collection of Cell Range → For Each Cell In Range(“B1:B100”)
✓ Each Chart in a collection of Charts in a Sheet, etc. → For Each Cht In Sheets(“Sheet1”).ChartObjects
Syntax: Example:
For instance,
• Workbook open
• Before workbook close
• Worksheet is activated
• Before a worksheet is deactivated
• Data in a cell is entered or edited
1
2
Of the above options, the second one viz. ‘Disable all macros with notification’ is recommended
3
5