Microsoft Excel Mastery
Part IX: Automation with Macros & VBA
Master Excel automation from recording simple macros to building professional VBA applications â with real Indian business examples.
đ¯ 7 Chapters | đģ 88+ Solved Examples | đ 35 MCQs | đī¸ 7 Mini Projects
Macros â Recording & Running Automated Tasks
đĸ Why Macros Matter in Indian Business
At Tata Consultancy Services (TCS), finance teams process 50,000+ invoices monthly. Before macros, an analyst spent 3 hours daily formatting reports â applying headers, borders, column widths, and number formats. After recording just 4 macros, the same task takes under 2 minutes. That's âš18 lakh saved annually per team in productivity.
TCSInfosysWiproRelianceđ Learning Objectives
- Understand what macros are and why they automate repetitive tasks
- Enable the Developer tab and record your first macro
- Run macros via the ribbon, shortcut keys, and buttons
- Differentiate between absolute and relative recording
- Configure macro security settings and save as
.xlsm - Use the Personal Macro Workbook for cross-file macros
What Are Macros?
A macro is a recorded sequence of actions in Excel that can be replayed with a single click or shortcut key. Think of it like a TV remote's "macro button" â one press turns on the TV, sets the volume, and switches to your favourite channel. In Excel, a macro might select a range, apply bold formatting, add borders, set column widths, and freeze panes â all automatically.
Behind the scenes, when you record a macro, Excel writes VBA (Visual Basic for Applications) code that represents every action you performed. You don't need to know VBA to record macros â Excel does the coding for you.
Step 1: Enabling the Developer Tab
The Developer tab is hidden by default in Excel. You must enable it before recording macros.
- Go to
File â Options - Click Customize Ribbon in the left panel
- In the right panel under "Main Tabs", check the box next to Developer
- Click OK
Step 2: Recording a Macro
- Click
Developer â Record Macro - In the dialog box:
- Macro name: e.g.,
FormatReport(no spaces, start with letter) - Shortcut key: e.g., Ctrl+Shift+F
- Store macro in: This Workbook / New Workbook / Personal Macro Workbook
- Description: "Applies standard header formatting to reports"
- Macro name: e.g.,
- Click OK â recording starts (notice the blue square in the status bar)
- Perform your actions (format cells, adjust widths, etc.)
- Click
Developer â Stop Recording
Format Report â and 1stMacro â will cause errors. Use FormatReport â
or Macro_Format â
instead.Step 3: Running Macros
Three ways to run a recorded macro:
| Method | Steps | Best For |
|---|---|---|
| Ribbon | Developer â Macros â Select â Run | Occasional use |
| Shortcut Key | Press assigned shortcut (e.g., Ctrl+Shift+F) | Frequent use |
| Button | Developer â Insert â Button â Assign Macro | Other users |
Relative vs Absolute Recording
This is one of the most important concepts in macro recording:
| Feature | Absolute (Default) | Relative |
|---|---|---|
| Cell references | Records exact cell (e.g., A1) | Records offset (e.g., 2 rows down) |
| Use case | Always format same range | Format starting from current cell |
| Toggle | Default mode | Developer â Use Relative References |
| VBA code | Range("A1").Select | ActiveCell.Offset(1, 0).Select |
Macro Security Settings
Navigate to File â Options â Trust Center â Trust Center Settings â Macro Settings:
| Setting | Description | Recommended |
|---|---|---|
| Disable all macros without notification | Blocks everything silently | High-security environments |
| Disable all macros with notification | Shows warning bar to enable | â Best for most users |
| Disable except digitally signed | Only signed macros run | Corporate environments |
| Enable all macros | Runs everything â dangerous! | â Never in production |
Saving as .xlsm (Macro-Enabled Workbook)
Standard .xlsx files cannot store macros. When you save a workbook containing macros, Excel will prompt you to save as .xlsm (macro-enabled). If you save as .xlsx, all macros are stripped out permanently!
Personal Macro Workbook (PERSONAL.XLSB)
The Personal Macro Workbook is a hidden workbook that opens automatically every time Excel starts. Macros stored here are available in every workbook you open â perfect for universal formatting macros.
- When recording, set "Store macro in" to Personal Macro Workbook
- Excel creates
PERSONAL.XLSBin:C:\Users\[Name]\AppData\Roaming\Microsoft\Excel\XLSTART\ - To edit:
View â Unhide â PERSONAL.XLSB
Solved Examples
Example 1: Record a Formatting Macro
Task: Record a macro that formats any selected range with bold headers, borders, and auto-fit columns.
Steps:
- Select range A1:E1 (headers)
Developer â Record Macroâ Name:FormatHeaders, Shortcut: Ctrl+Shift+H- Apply Bold, Font Size 12, Fill Color: Dark Green
- Select A1:E20 â Apply All Borders
- Select columns A:E â AutoFit Column Width
Developer â Stop Recording
Generated VBA Code:
VBA Sub FormatHeaders() Range("A1:E1").Select With Selection.Font .Bold = True .Size = 12 End With Selection.Interior.Color = RGB(5, 150, 105) Range("A1:E20").Borders.LineStyle = xlContinuous Columns("A:E").AutoFit End Sub
Example 2: GST Invoice Formatter
Scenario: A Flipkart seller receives daily sales data. Record a macro to add GST columns.
| Product | Price (âš) | Qty |
|---|---|---|
| Mobile Cover | 299 | 50 |
| USB Cable | 149 | 120 |
| Screen Guard | 199 | 85 |
Macro adds columns: Subtotal = Price à Qty, CGST (9%) = Subtotal à 0.09, SGST (9%) = same, Total = Subtotal + CGST + SGST.
VBA Sub AddGSTColumns() Range("D1").Value = "Subtotal" Range("E1").Value = "CGST 9%" Range("F1").Value = "SGST 9%" Range("G1").Value = "Total" Range("D2").Formula = "=B2*C2" Range("E2").Formula = "=D2*0.09" Range("F2").Formula = "=D2*0.09" Range("G2").Formula = "=D2+E2+F2" Range("D2:G2").AutoFill Destination:=Range("D2:G4") Range("D2:G4").NumberFormat = "âš#,##0.00" End Sub
Example 3â6: Quick Recording Tasks
Ex 3: Macro to freeze top row and apply filter to row 1. Ex 4: Macro to insert current date in selected cell with Date function. Ex 5: Macro to sort column A ascending (AâZ). Ex 6: Macro to set print area to used range and landscape orientation.
Example 7: Relative Reference â Data Entry Template
Task: Record with relative references to enter "Name", "Amount", "Date" headers and move down.
VBA Sub DataTemplate() ActiveCell.Value = "Name" ActiveCell.Offset(0, 1).Value = "Amount (âš)" ActiveCell.Offset(0, 2).Value = "Date" ActiveCell.Offset(1, 0).Select End Sub
Examples 8â12: Business Scenarios
Ex 8: Macro to highlight negative values red in selection. Ex 9: Macro to remove duplicates from column A. Ex 10: Auto-save backup copy with timestamp in filename. Ex 11: Macro to merge and center title row across A1:F1. Ex 12: Macro to convert text-formatted numbers to actual numbers using Paste Special â Multiply by 1.
Practice Exercises
- Enable the Developer tab on your Excel installation and take a screenshot of the ribbon showing the Developer tab.
- Record a macro called
BasicFormatthat applies Arial font size 11, cell color light yellow, and all borders to the selection. - Record the same formatting macro using Relative References. Compare the VBA code generated.
- Create a button on your worksheet and assign the
BasicFormatmacro to it. - Save a workbook with macros as both
.xlsxand.xlsm. Document what happens to the macros. - Store a macro in PERSONAL.XLSB, close Excel, reopen, and verify the macro is available in a new blank workbook.
MCQ Quiz
What file format must be used to save macros?
- .xlsx
- .xlsm
- .xls
- .csv
Which tab contains the Record Macro button?
- Home
- Insert
- Developer
- View
Relative references in macro recording use which VBA method?
- Range("A1").Select
- ActiveCell.Offset(row, col).Select
- Cells(1,1).Select
- Selection.Value
Where is PERSONAL.XLSB stored?
- Desktop
- Documents folder
- XLSTART folder in AppData
- Program Files
The recommended macro security setting for most users is:
- Enable all macros
- Disable all without notification
- Disable all with notification
- Disable except digitally signed
đŧ Interview Q1: What is the difference between .xlsx and .xlsm?
Answer: .xlsx is the standard Excel format that cannot contain macros or VBA code. .xlsm is the macro-enabled format that preserves all VBA modules, macros, and UserForms. If you save a macro workbook as .xlsx, all macros are permanently deleted. In enterprise environments, many email systems block .xlsm attachments for security reasons, which is an important consideration.
đŧ Interview Q2: Explain Absolute vs Relative recording.
Answer: Absolute recording captures exact cell references (Range("A1")), so the macro always operates on the same cells. Relative recording uses ActiveCell.Offset, recording the movement pattern from wherever the cursor currently is. Use absolute for fixed-layout reports; use relative for repeatable data entry patterns.
đŧ Interview Q3: What is PERSONAL.XLSB and when would you use it?
Answer: PERSONAL.XLSB is a hidden workbook stored in the XLSTART folder that loads automatically with Excel. Macros stored here are available globally across all workbooks. Use it for universal utilities like formatting shortcuts, date stamping, or navigation macros that you need in every file.
- Alt+F8 â Open Macro dialog box
- Alt+F11 â Open VBA Editor
- Ctrl+Shift+[key] â Run assigned macro shortcut
đī¸ Mini Project: Report Formatting Macro Suite
Problem: Create a set of 4 macros for standardizing monthly sales reports at a retail company:
- FormatHeader â Bold, size 14, dark green fill, white font for row 1
- ApplyBorders â All borders for used range, thick outside border
- SetColumnWidths â Column A=25, B-D=15, E-F=18; AutoFit remaining
- FreezePanes â Freeze top row and apply AutoFilter
Bonus: Create a 5th macro RunAll that calls all four in sequence. Assign to a button labeled "đ Format Report".
Deliverables: .xlsm file with all macros, sample data (10 products with sales), and a button to execute.
đ Chapter 37 Summary
- Macros record repetitive actions as replayable VBA code
- Enable Developer tab via File â Options â Customize Ribbon
- Record with Developer â Record Macro; stop with Stop Recording
- Run via Developer â Macros, shortcut key, or assigned button
- Absolute = fixed cells; Relative = offset from current cell
- Save as .xlsm to preserve macros; .xlsx deletes them
- PERSONAL.XLSB stores macros available across all workbooks
- Set macro security to "Disable with notification" for safety
VBA Fundamentals â Your First Code
đ From Recording to Real Programming
Recording macros is powerful, but it's like using a calculator â limited to what buttons exist. VBA (Visual Basic for Applications) is the programming language behind Excel that lets you build anything: interactive dashboards, automated reports, data validation engines, and even full business applications. At Reliance Industries, custom VBA tools process inventory data across 15,000+ retail stores daily.
RelianceMahindraHDFC Bankđ Learning Objectives
- Navigate the VBA Editor (VBE) and its components
- Write and run Sub procedures
- Use MsgBox and InputBox for user interaction
- Manipulate cells using Range and Cells objects
- Use With...End With for cleaner code
The VBA Editor (VBE)
Press Alt+F11 to open the VBA Editor. It has four key areas:
| Component | Location | Purpose |
|---|---|---|
| Project Explorer | Top-left | Shows all open workbooks, sheets, modules |
| Properties Window | Bottom-left | Properties of selected object |
| Code Window | Center | Where you write/edit VBA code |
| Immediate Window | Bottom (Ctrl+G) | Test expressions, Debug.Print output |
Inserting a Module
VBA code is stored in modules. To create one: In the VBE, click Insert â Module. A new module (Module1) appears in the Project Explorer under your workbook.
Sub Procedures
Every macro is a Sub procedure â a block of code that performs actions:
VBA Sub MyFirstMacro() ' This is a comment - Excel ignores this line MsgBox "Hello, Excel!" End Sub
Run it by pressing F5 or clicking the green âļ Run button. A dialog box appears with "Hello, Excel!"
MsgBox â Displaying Messages
MsgBox displays information and can include buttons and icons:
VBA ' Simple message MsgBox "Report generated successfully!" ' With title MsgBox "Saved!", vbInformation, "Status" ' With Yes/No buttons Dim result As VbMsgBoxResult result = MsgBox("Delete all data?", vbYesNo + vbCritical, "Warning") If result = vbYes Then Range("A2:E100").ClearContents End If
| Constant | Effect |
|---|---|
vbOKOnly | OK button (default) |
vbYesNo | Yes and No buttons |
vbYesNoCancel | Yes, No, Cancel buttons |
vbInformation | âšī¸ Info icon |
vbExclamation | â ī¸ Warning icon |
vbCritical | â Error icon |
InputBox â Getting User Input
VBA Sub GetStudentName() Dim studentName As String studentName = InputBox("Enter student name:", "CBSE Report Card") If studentName <> "" Then Range("A1").Value = studentName MsgBox "Welcome, " & studentName & "!" End If End Sub
Range Object â Manipulating Cells
The Range object is the most-used object in VBA. It represents cells:
VBA ' Set a value Range("A1").Value = "Employee Name" ' Read a value Dim salary As Double salary = Range("B5").Value ' Using Cells(row, column) - great for loops Cells(1, 1).Value = "Name" ' Same as Range("A1") Cells(3, 2).Value = 45000 ' Same as Range("B3") ' Select and format a range Range("A1:D1").Font.Bold = True Range("A1:D1").Interior.Color = RGB(5, 150, 105) ' Clear contents Range("A2:D100").ClearContents
Worksheets and Workbooks Objects
VBA ' Reference a specific sheet Worksheets("Sales").Range("A1").Value = "Monthly Sales" ' Add a new sheet Worksheets.Add.Name = "Summary" ' Reference another workbook Workbooks("Data.xlsx").Worksheets("Sheet1").Range("A1").Value ' Active objects ActiveWorkbook.Save ActiveSheet.Name = "Report" ActiveCell.Value = "Hello"
With...End With Statement
Instead of repeating the object reference, use With:
VBA ' Without With (repetitive) Range("A1").Font.Bold = True Range("A1").Font.Size = 14 Range("A1").Font.Color = vbWhite Range("A1").Interior.Color = RGB(5,150,105) ' With With (clean!) With Range("A1") .Font.Bold = True .Font.Size = 14 .Font.Color = vbWhite .Interior.Color = RGB(5, 150, 105) End With
Solved Examples (15)
Example 1: Salary Calculator
VBA Sub SalaryCalculator() Dim basic As Double, hra As Double, da As Double, gross As Double basic = InputBox("Enter Basic Salary (âš):") hra = basic * 0.4 ' 40% HRA da = basic * 0.12 ' 12% DA gross = basic + hra + da MsgBox "Basic: âš" & basic & vbCrLf & _ "HRA: âš" & hra & vbCrLf & _ "DA: âš" & da & vbCrLf & _ "Gross: âš" & gross, vbInformation, "Salary Slip" End Sub
Example 2: Write Data Table to Sheet
VBA Sub CreateStudentTable() ' Headers Range("A1").Value = "Roll No" Range("B1").Value = "Name" Range("C1").Value = "Marks" Range("D1").Value = "Grade" ' Data Range("A2").Value = 101: Range("B2").Value = "Aarav Sharma" Range("C2").Value = 92: Range("D2").Value = "A+" Range("A3").Value = 102: Range("B3").Value = "Priya Patel" Range("C3").Value = 87: Range("D3").Value = "A" ' Format headers With Range("A1:D1") .Font.Bold = True .Interior.Color = RGB(5, 150, 105) .Font.Color = vbWhite End With End Sub
Example 3: GST Calculator with InputBox
VBA Sub GSTCalculator() Dim amount As Double, gstRate As Double amount = InputBox("Enter amount (âš):") gstRate = InputBox("Enter GST rate (5/12/18/28):") Dim cgst As Double, sgst As Double, total As Double cgst = amount * (gstRate / 200) sgst = cgst total = amount + cgst + sgst MsgBox "Amount: âš" & amount & vbCrLf & _ "CGST (" & gstRate / 2 & "%): âš" & Format(cgst, "#,##0.00") & vbCrLf & _ "SGST (" & gstRate / 2 & "%): âš" & Format(sgst, "#,##0.00") & vbCrLf & _ "Total: âš" & Format(total, "#,##0.00"), vbInformation, "GST Bill" End Sub
Example 4: Confirmation Before Delete
VBA Sub ConfirmDelete() Dim ans As VbMsgBoxResult ans = MsgBox("This will delete all data in Sheet1. Continue?", _ vbYesNo + vbCritical, "â ī¸ Confirm Delete") If ans = vbYes Then Worksheets("Sheet1").Cells.ClearContents MsgBox "All data cleared.", vbInformation Else MsgBox "Operation cancelled." End If End Sub
Examples 5â15 (Summary)
Ex 5: Copy range A1:D10 from Sheet1 to Sheet2. Ex 6: Rename active sheet using InputBox. Ex 7: Count filled rows in column A using Cells(Rows.Count, 1).End(xlUp).Row. Ex 8: Create a new workbook and copy summary data. Ex 9: Format currency columns with âš symbol. Ex 10: Toggle gridlines on/off. Ex 11: Add a timestamp to cell A1 with Now. Ex 12: Set zoom to 120% for all sheets. Ex 13: Protect sheet with password from InputBox. Ex 14: Insert a row above current cell. Ex 15: Multi-sheet summary â read A1 from all sheets into a new sheet.
Practice Exercises
- Write a Sub that displays your name, college, and favorite subject using MsgBox with vbInformation.
- Create a VBA program that asks for length and breadth via InputBox and calculates area of a rectangle.
- Write VBA to populate A1:A12 with month names (January to December) using Cells().
- Use With...End With to format range B2:B10 â font Calibri, size 11, bold, blue color.
- Write VBA to create a new worksheet named "Analysis" and write "Report Date:" in A1 with today's date in B1.
- Create a simple âš to $ converter: InputBox for âš amount, multiply by 0.012, show result in MsgBox.
- Write VBA that reads employee name from A2 and salary from B2, calculates 10% bonus, writes to C2.
- Create a MsgBox with Yes/No/Cancel buttons that asks "Save changes?" and shows different messages based on choice.
MCQ Quiz
What keyboard shortcut opens the VBA Editor?
- Ctrl+F11
- Alt+F11
- F11
- Shift+F11
Which VBA function displays a dialog box and gets user text input?
- MsgBox
- InputBox
- TextBox
- GetInput
Cells(3, 2) refers to which cell?
- C2
- B3
- C3
- B2
What does the ' character do in VBA?
- String delimiter
- Starts a comment
- Concatenation
- Line continuation
The With...End With statement is used to:
- Create loops
- Handle errors
- Avoid repeating the same object reference
- Declare variables
đŧ Interview Q1: What is the difference between Range and Cells?
Range("A1") uses string notation and can reference single cells, ranges ("A1:D10"), or named ranges. Cells(row, col) uses numeric row/column numbers, making it ideal for loops. Cells(i, j) where i and j are variables is much easier than building Range strings dynamically.
đŧ Interview Q2: How do you find the last used row in VBA?
Use: lastRow = Cells(Rows.Count, 1).End(xlUp).Row. This starts from the bottom of column 1 (row 1,048,576) and moves up to the first non-empty cell â equivalent to pressing Ctrl+Up from the bottom.
đŧ Interview Q3: What does vbCrLf do?
vbCrLf is a VBA constant for carriage return + line feed (new line character). It's used in MsgBox and string concatenation to create multi-line messages.
- Alt+F11 â Open/close VBA Editor
- F5 â Run current Sub procedure
- Ctrl+G â Open Immediate Window
- F2 â Open Object Browser
đī¸ Mini Project: Interactive Greeting Generator
Task: Build a VBA macro that:
- Asks for user's name via InputBox
- Asks for their department (Sales/HR/IT/Finance)
- Creates a new worksheet named after the user
- Writes a personalized header: "Welcome, [Name]! â [Department]"
- Formats the header with the company color scheme
- Adds current date, time, and "Report prepared by: [Name]" at the bottom
- Shows a MsgBox confirmation with vbInformation
đ Chapter 38 Summary
- VBA Editor opens with Alt+F11; code lives in Modules
- Sub procedures:
Sub Name() ... End Sub - MsgBox displays output; InputBox gets text input
- Range("A1") and Cells(1,1) both reference cell A1
- With...End With reduces repetitive object references
- Comments start with apostrophe (')
- Line continuation: space + underscore ( _) at end of line