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
VBA Variables & Data Types
đ Learning Objectives
- Declare variables with Dim, Private, and Public
- Choose appropriate data types for different scenarios
- Use Option Explicit to enforce declarations
- Work with constants, arrays, and type conversion functions
Declaring Variables with Dim
Variables store data values. Always declare them with Dim:
VBA Dim studentName As String Dim marks As Integer Dim percentage As Double Dim isPassed As Boolean Dim examDate As Date studentName = "Rahul Verma" marks = 456 percentage = marks / 5 ' 91.2 isPassed = (percentage >= 33) examDate = #3/15/2025#
VBA Data Types
| Data Type | Size | Range | Example Use |
|---|---|---|---|
Integer | 2 bytes | -32,768 to 32,767 | Roll number, quantity |
Long | 4 bytes | -2.1 billion to 2.1 billion | Row count, large IDs |
Single | 4 bytes | Âą3.4 à 10Âŗâ¸ | Approximate decimals |
Double | 8 bytes | Âą1.8 à 10Âŗâ°â¸ | Salary, GST, financial |
String | Varies | Up to 2 billion chars | Names, addresses |
Boolean | 2 bytes | True or False | Pass/fail, yes/no |
Date | 8 bytes | 1/1/100 to 12/31/9999 | Dates and times |
Variant | 16+ bytes | Any type (slow) | Avoid if possible |
Object | 4 bytes | Any object reference | Range, Worksheet |
Integer for row numbers causes overflow errors in modern Excel (1,048,576 rows exceeds Integer's 32,767 limit). Always use Long for row/column counters.Option Explicit
Add Option Explicit at the very top of every module. This forces you to declare all variables, catching typos:
VBA Option Explicit Sub Example() Dim totalSales As Double totalSales = 50000 ' totlSales = 50000 â This typo would cause a compile error! End Sub
Tools â Options â Editor tab â check "Require Variable Declaration".Constants
VBA Const GST_RATE As Double = 0.18 Const COMPANY_NAME As String = "Reliance Retail" Const MAX_STUDENTS As Long = 500 Const PI As Double = 3.14159265
Variable Scope
| Scope | Declaration | Accessible From |
|---|---|---|
| Procedure Level | Dim x As Integer (inside Sub) | Only within that Sub |
| Module Level | Private x As Integer (top of module) | Any Sub in that module |
| Global | Public x As Integer (top of module) | Any Sub in any module |
Arrays
VBA ' Static array Dim marks(1 To 5) As Integer marks(1) = 85 marks(2) = 92 marks(3) = 78 marks(4) = 95 marks(5) = 88 ' Dynamic array Dim students() As String Dim n As Long n = Cells(Rows.Count, 1).End(xlUp).Row ReDim students(1 To n) ' 2D array for table data Dim table(1 To 10, 1 To 3) As Variant
Type Conversion Functions
| Function | Converts To | Example |
|---|---|---|
CInt() | Integer | CInt("42") â 42 |
CLng() | Long | CLng("100000") â 100000 |
CDbl() | Double | CDbl("99.5") â 99.5 |
CStr() | String | CStr(42) â "42" |
CDate() | Date | CDate("15-Mar-2025") |
CBool() | Boolean | CBool(1) â True |
Solved Examples
Example 1: Student Marks Processor
VBA Sub ProcessMarks() Dim subjects(1 To 5) As String Dim marks(1 To 5) As Integer Dim total As Long, avg As Double, i As Integer subjects(1) = "Hindi": marks(1) = 82 subjects(2) = "English": marks(2) = 91 subjects(3) = "Maths": marks(3) = 95 subjects(4) = "Science": marks(4) = 88 subjects(5) = "SST": marks(5) = 79 total = 0 For i = 1 To 5 Cells(i + 1, 1).Value = subjects(i) Cells(i + 1, 2).Value = marks(i) total = total + marks(i) Next i avg = total / 5 Cells(7, 1).Value = "Average" Cells(7, 2).Value = Format(avg, "0.00") End Sub
Example 2: Dynamic Array from Sheet Data
VBA Sub ReadToArray() Dim lastRow As Long, i As Long lastRow = Cells(Rows.Count, 1).End(xlUp).Row Dim names() As String ReDim names(1 To lastRow - 1) For i = 2 To lastRow names(i - 1) = Cells(i, 1).Value Next i MsgBox "Loaded " & UBound(names) & " names into array." End Sub
Examples 3â12: EMI calculator with Double, Boolean pass/fail checker, Date difference calculator for employee tenure, Constant-based tax slab calculator, 2D array for 5Ã3 marks table, ReDim Preserve to grow array, Type conversion for string-to-number cleanup, Module-level variable counter, Public variable shared across modules, Array-based Indian state capital quiz.
MCQ Quiz
Which data type should you use for Excel row numbers?
- Integer
- Long
- Single
- Byte
What does Option Explicit do?
- Makes all variables public
- Forces variable declaration before use
- Enables error handling
- Turns on line numbers
ReDim is used to:
- Delete an array
- Resize a dynamic array
- Declare a constant
- Convert data types
CStr(100) returns:
- 100 (Integer)
- "100" (String)
- True
- Error
A Public variable declared at module level is accessible:
- Only in that procedure
- Only in that module
- In all modules of the project
- Only in UserForms
đŧ Interview Q1: Why avoid Variant data type?
Variant consumes 16+ bytes (vs 4 for Long), is slower because VBA must determine the type at runtime, and hides bugs since it accepts any value without type checking. Use explicit types for better performance, readability, and debugging.
đŧ Interview Q2: Difference between ReDim and ReDim Preserve?
ReDim resizes the array but erases all existing data. ReDim Preserve resizes while keeping existing values. Note: with Preserve, you can only resize the last dimension of a multi-dimensional array.
đŧ Interview Q3: Explain variable scope in VBA.
Procedure-level (Dim inside Sub): exists only during that Sub's execution. Module-level (Private at top): shared across all Subs in that module, persists while workbook is open. Global (Public at top): accessible from any module in the project.
- Ctrl+Space â Auto-complete variable/keyword in VBE
- Ctrl+J â List properties/methods
đī¸ Mini Project: CBSE Grade Calculator
Build a VBA program that: (1) Uses arrays for 5 subjects and marks, (2) Calculates total, average, percentage, (3) Assigns CBSE grades (A1: 91-100, A2: 81-90, B1: 71-80, B2: 61-70, C1: 51-60, C2: 41-50, D: 33-40, E: below 33), (4) Writes everything to worksheet with formatting, (5) Uses Constants for grade boundaries, (6) Uses Boolean to check pass/fail (minimum 33 in each subject).
đ Chapter 39 Summary
- Dim declares variables:
Dim x As Long - Use Long (not Integer) for row counts; Double for financial data
- Option Explicit catches typos at compile time
- Const for values that never change (GST rates, PI)
- Scope: Dim=procedure, Private=module, Public=global
- Arrays: static (
Dim a(1 To 10)) and dynamic (ReDim) - Type conversion: CInt, CLng, CDbl, CStr, CDate
VBA Loops & Control Structures
⥠Processing 10,000 Rows in Seconds
At Zomato, daily restaurant data has 10,000+ rows of orders. Loops let VBA process every row automatically â checking delivery times, flagging delays, calculating commissions. What takes a human 4 hours takes a VBA loop under 3 seconds.
ZomatoSwiggyBigBasketđ Learning Objectives
- Use If...Then...ElseIf for decision-making
- Use Select Case for multi-branch logic
- Master For...Next, For Each, Do While, Do Until loops
- Apply loops to real worksheet data processing
If...Then...Else
VBA Sub CheckPassFail() Dim marks As Integer marks = Range("B2").Value If marks >= 90 Then Range("C2").Value = "Distinction" ElseIf marks >= 75 Then Range("C2").Value = "First Class" ElseIf marks >= 60 Then Range("C2").Value = "Second Class" ElseIf marks >= 33 Then Range("C2").Value = "Pass" Else Range("C2").Value = "Fail" End If End Sub
Select Case
VBA Sub AssignGSTRate() Dim category As String, rate As Double category = Range("A2").Value Select Case category Case "Food Grains", "Milk" rate = 0 ' Exempt Case "Packaged Food" rate = 5 Case "Electronics" rate = 18 Case "Luxury", "Automobile" rate = 28 Case Else rate = 12 ' Default End Select Range("B2").Value = rate & "%" End Sub
For...Next Loop
VBA Sub FillSerialNumbers() Dim i As Long For i = 1 To 100 Cells(i + 1, 1).Value = i Next i End Sub ' With Step Sub FillEvenNumbers() Dim i As Long, row As Long row = 2 For i = 2 To 100 Step 2 Cells(row, 1).Value = i row = row + 1 Next i End Sub
For Each...Next Loop
VBA Sub HighlightNegatives() Dim cell As Range For Each cell In Range("B2:B100") If IsNumeric(cell.Value) And cell.Value < 0 Then cell.Interior.Color = RGB(255, 200, 200) cell.Font.Color = vbRed End If Next cell End Sub
Do While / Do Until Loops
VBA ' Process rows until empty cell found Sub ProcessUntilEmpty() Dim row As Long row = 2 Do While Cells(row, 1).Value <> "" ' Calculate total in column D Cells(row, 4).Value = Cells(row, 2).Value * Cells(row, 3).Value row = row + 1 Loop MsgBox "Processed " & (row - 2) & " rows." End Sub
Nested Loops â Multiplication Table
VBA Sub MultiplicationTable() Dim i As Long, j As Long For i = 1 To 10 Cells(1, i + 1).Value = i ' Column headers Cells(i + 1, 1).Value = i ' Row headers For j = 1 To 10 Cells(i + 1, j + 1).Value = i * j Next j Next i End Sub
Exit Statements
VBA ' Exit For â search for a value and stop when found Sub FindEmployee() Dim i As Long, searchName As String searchName = InputBox("Enter employee name:") For i = 2 To 1000 If Cells(i, 1).Value = searchName Then MsgBox "Found at row " & i & "! Salary: âš" & Cells(i, 3).Value Exit For End If Next i End Sub
Practical: Zomato Order Processor
| Order ID | Restaurant | Amount (âš) | Delivery (min) | Status |
|---|---|---|---|---|
| Z001 | Haldiram's | 450 | 25 | |
| Z002 | Domino's | 680 | 45 | |
| Z003 | Biryani Blues | 320 | 30 |
VBA Sub ProcessZomatoOrders() Dim lastRow As Long, i As Long Dim onTime As Long, delayed As Long lastRow = Cells(Rows.Count, 1).End(xlUp).Row For i = 2 To lastRow If Cells(i, 4).Value <= 30 Then Cells(i, 5).Value = "On Time â " Cells(i, 5).Interior.Color = RGB(209, 250, 229) onTime = onTime + 1 Else Cells(i, 5).Value = "Delayed â" Cells(i, 5).Interior.Color = RGB(254, 202, 202) delayed = delayed + 1 End If Next i MsgBox "On Time: " & onTime & vbCrLf & "Delayed: " & delayed End Sub
Practice Exercises
- Write a For loop to fill cells A1:A20 with squares (1, 4, 9, 16...).
- Use For Each to count how many cells in B2:B50 contain the word "Pending".
- Write a Do While loop that reads names from column A until it finds "END".
- Use Select Case to assign Indian tax slabs (0-2.5L=0%, 2.5-5L=5%, 5-10L=20%, 10L+=30%).
- Nested loop: Create a 12Ã12 multiplication table starting at A1.
- Write a loop to find the maximum value in column C (without using WorksheetFunction.Max).
- Process a Flipkart order list: loop through rows, apply 10% discount if Amount > âš1000, write discounted price in next column.
- Write a loop with Exit For that searches column A for a specific employee ID.
MCQ Quiz
Which loop is best for iterating through all cells in a Range?
- For...Next
- For Each...Next
- Do While
- While...Wend
What does Exit For do?
- Exits the program
- Exits only the innermost For loop
- Exits all loops
- Skips current iteration
Select Case is an alternative to:
- For loops
- Nested If...ElseIf
- Do While
- With...End With
For i = 10 To 1 Step -1 counts:
- 1 to 10
- 10 down to 1
- Only even numbers
- Error
Do Until condition is True is equivalent to:
- Do While condition is True
- Do While condition is False
- For Each
- Select Case
đŧ Interview Q1: For Each vs For...Next â when to use which?
Use For Each when iterating through a collection (cells in a range, sheets in a workbook) where you don't need the index. Use For...Next when you need the counter variable (row number, column index) or need to iterate in reverse/with a step.
đŧ Interview Q2: How to avoid infinite Do While loops?
Always ensure the loop condition will eventually become False. Include a counter limit: Do While condition And counter < 100000. Also ensure the variable in the condition is modified inside the loop (e.g., row = row + 1).
đŧ Interview Q3: How do you speed up VBA loops that process thousands of rows?
Add Application.ScreenUpdating = False at the start and restore to True at the end. Also use Application.Calculation = xlCalculationManual and restore to xlAutomatic. Read data into an array first, process in memory, then write back â this avoids thousands of cell read/writes.
- F8 â Step through code line by line (debugging)
- Ctrl+Break â Stop a running macro / infinite loop
- F5 â Run / continue execution
đī¸ Mini Project: Automated Data Processor
Scenario: An Indian retailer has 100 rows of sales data with columns: Product, Category, Price, Quantity, Region.
Requirements:
- Loop through all rows and calculate Total (Price à Qty) in column F
- Use Select Case on Category to assign GST rates (Food=5%, Clothing=12%, Electronics=18%, Luxury=28%)
- Calculate GST Amount and Grand Total in columns G and H
- Highlight rows where Grand Total > âš10,000 in light green
- Highlight rows where Grand Total < âš500 in light red
- At the bottom, show summary: Count, Sum, Average, Max, Min for Grand Total
- Use Application.ScreenUpdating = False for performance
đ Chapter 40 Summary
- If...Then...ElseIf...Else for conditional decisions
- Select Case for clean multi-option branching
- For i = start To end [Step n] ... Next i for counted loops
- For Each item In collection ... Next item for collections
- Do While / Do Until for condition-based loops
- Exit For / Exit Do / Exit Sub to break out early
- Always ensure loops have termination conditions
VBA UserForms â Building Interactive Interfaces
đĨī¸ Professional Data Entry for Indian Businesses
At HDFC Bank, loan officers use Excel-based UserForms to capture customer applications â name, PAN, Aadhaar, income, loan amount. These forms include validation (PAN format: ABCDE1234F), dropdowns for branch names, and automatic data storage. No raw spreadsheet editing = fewer errors, better UX.
HDFC BankSBILICđ Learning Objectives
- Create and design UserForms with Toolbox controls
- Set control properties (Name, Caption, Font, etc.)
- Write event procedures for buttons and form interaction
- Validate form input before saving to worksheet
- Navigate between records (Previous, Next, First, Last)
Creating a UserForm
In VBE: Insert â UserForm. A blank form canvas appears with the Toolbox panel.
Toolbox Controls
| Control | Purpose | Key Properties |
|---|---|---|
| Label | Display text (e.g., "Name:") | Caption, Font, ForeColor |
| TextBox | User text input | Name, Value, MaxLength |
| ComboBox | Dropdown selection | List, Value, RowSource |
| ListBox | Multi-item selection list | List, MultiSelect |
| CheckBox | True/false toggle | Value, Caption |
| OptionButton | Mutually exclusive choice | Value, GroupName |
| CommandButton | Clickable action button | Caption, Default, Cancel |
| Frame | Group related controls | Caption |
| SpinButton | Increment/decrement value | Min, Max, Value |
| Image | Display picture | Picture, PictureSizeMode |
Setting Properties
Select a control, then modify properties in the Properties Window (F4):
| Property | What It Does | Example |
|---|---|---|
| Name | Code reference name | txtStudentName |
| Caption | Displayed text | "Enter Student Name" |
| Font | Font settings | Calibri, 11pt |
| BackColor | Background color | &H00C0FFC0 (light green) |
| Enabled | Can user interact? | True / False |
| Visible | Is it shown? | True / False |
txt for TextBox, cmb for ComboBox, cmd for CommandButton, opt for OptionButton, chk for CheckBox, lbl for Label, frm for Frame.Event Procedures
VBA ' CommandButton Click â Save data to worksheet Private Sub cmdSave_Click() Dim nextRow As Long nextRow = Worksheets("Students").Cells(Rows.Count, 1).End(xlUp).Row + 1 With Worksheets("Students") .Cells(nextRow, 1).Value = txtRollNo.Value .Cells(nextRow, 2).Value = txtName.Value .Cells(nextRow, 3).Value = cmbClass.Value .Cells(nextRow, 4).Value = CDbl(txtMarks.Value) If optMale.Value Then .Cells(nextRow, 5).Value = "Male" Else .Cells(nextRow, 5).Value = "Female" End If End With MsgBox "Student record saved!", vbInformation ' Clear form txtRollNo.Value = "" txtName.Value = "" txtMarks.Value = "" txtRollNo.SetFocus End Sub ' UserForm Initialize â load default values Private Sub UserForm_Initialize() cmbClass.AddItem "Class 9" cmbClass.AddItem "Class 10" cmbClass.AddItem "Class 11" cmbClass.AddItem "Class 12" cmbClass.ListIndex = 0 ' Select first item optMale.Value = True End Sub
Form Validation
VBA Private Sub cmdSave_Click() ' Validate empty fields If Trim(txtName.Value) = "" Then MsgBox "Name cannot be empty!", vbExclamation txtName.SetFocus: Exit Sub End If ' Validate numeric If Not IsNumeric(txtMarks.Value) Then MsgBox "Marks must be a number!", vbExclamation txtMarks.SetFocus: Exit Sub End If ' Validate range If CDbl(txtMarks.Value) < 0 Or CDbl(txtMarks.Value) > 100 Then MsgBox "Marks must be 0â100!", vbExclamation txtMarks.SetFocus: Exit Sub End If ' All valid â save data... End Sub
Record Navigation
VBA Dim currentRow As Long Private Sub cmdNext_Click() Dim lastRow As Long lastRow = Cells(Rows.Count, 1).End(xlUp).Row If currentRow < lastRow Then currentRow = currentRow + 1 LoadRecord currentRow End If End Sub Private Sub LoadRecord(row As Long) txtRollNo.Value = Cells(row, 1).Value txtName.Value = Cells(row, 2).Value cmbClass.Value = Cells(row, 3).Value lblRecordNum.Caption = "Record: " & (row - 1) End Sub
Solved Examples (Summary)
Ex 1-3: Simple form with Label + TextBox + Save button; ComboBox for Indian states dropdown; OptionButton for gender selection. Ex 4-6: CheckBox for selecting subjects; SpinButton linked to age TextBox; ListBox showing saved records. Ex 7-9: Date validation using IsDate(); PAN number format validation using Like "?????####?"; Multi-field form clearing. Ex 10-12: Search form â enter Roll No and load matching record; Delete record confirmation; Export form data to new sheet.
Practice Exercises
- Create a UserForm with TextBoxes for Name, Age, City and a Save button that writes to Sheet1.
- Add a ComboBox with all 28 Indian states. Load the list in UserForm_Initialize.
- Add validation: Name must not be empty, Age must be 18-65, City must not be empty.
- Add Previous/Next buttons to navigate between saved records.
- Add a Search TextBox and Search button to find records by name.
- Create a form with CheckBoxes for skills (Excel, Word, PowerPoint, Tally) and store selected skills as comma-separated string.
MCQ Quiz
Which event fires when a UserForm first opens?
- Click
- Initialize
- Activate
- Load
Which method shows a UserForm?
- UserForm1.Display
- UserForm1.Show
- UserForm1.Open
- UserForm1.Run
What prefix should be used for TextBox names?
- cmd
- lbl
- txt
- cmb
OptionButtons within the same Frame are:
- Independent
- Mutually exclusive
- Always hidden
- Read-only
To hide a UserForm without closing it:
- Unload Me
- Me.Hide
- Me.Close
- Me.Visible = False
đŧ Interview Q1: Difference between Me.Hide and Unload Me?
Me.Hide hides the form but keeps it in memory â all TextBox values, variables, and states are preserved. Unload Me destroys the form completely, releasing memory and resetting all controls to defaults. Use Hide when you need to return to the form; Unload when you're done.
đŧ Interview Q2: How do you populate a ComboBox dynamically from a worksheet range?
Method 1: Set RowSource property to a named range like "Sheet1!A2:A20". Method 2: Loop in Initialize: For Each cell In Range("A2:A20"): cmbState.AddItem cell.Value: Next. Method 2 is more flexible as it auto-adjusts to data size.
đŧ Interview Q3: How do you prevent duplicate entries in a UserForm?
Before saving, loop through existing data to check if the key field (e.g., Roll No) already exists: For i = 2 To lastRow: If Cells(i, 1).Value = txtRollNo.Value Then MsgBox "Duplicate!": Exit Sub: Next. Alternatively, use WorksheetFunction.CountIf.
- F4 â Toggle Properties Window in VBE
- F7 â View code for selected object
- Shift+F7 â View form designer
đī¸ Mini Project: Student Data Entry Form
Build a complete UserForm with: TextBoxes for Roll No, Name, Marks (5 subjects); ComboBox for Class (9-12); OptionButtons for Gender (Male/Female); CheckBox for "Transport Required"; CommandButtons for Save, Clear, Close, Previous, Next. Include full validation, duplicate checking, and formatted worksheet storage.
đ Chapter 41 Summary
- UserForms provide professional data entry interfaces
- Key controls: TextBox, ComboBox, OptionButton, CommandButton
- Use naming prefixes: txt, cmb, cmd, opt, chk, lbl
- UserForm_Initialize loads defaults and dropdown data
- Always validate input before saving to worksheet
- Me.Hide preserves data; Unload Me destroys the form
VBA Error Handling & Debugging
đĄī¸ Building Bulletproof VBA Tools
At State Bank of India, a VBA tool processes loan applications. If one application has a missing date field and the code crashes mid-run, it could corrupt 500 records. Proper error handling ensures the tool logs the error, skips the bad record, and continues processing â like a professional software application.
SBIICICI BankAxis Bankđ Learning Objectives
- Understand runtime, compile, and logical errors
- Implement On Error GoTo, Resume Next, GoTo 0
- Use the Err object for error details
- Master debugging tools: breakpoints, Immediate Window, stepping
Types of Errors
| Type | When | Example | Detection |
|---|---|---|---|
| Compile Error | Before running | Misspelled keyword, missing End Sub | VBE catches automatically |
| Runtime Error | During execution | Division by zero, file not found | On Error handlers |
| Logical Error | Code runs but wrong result | Using + instead of * | Debugging, testing |
On Error GoTo ErrorHandler
VBA Sub SafeDivision() On Error GoTo ErrorHandler Dim num As Double, den As Double, result As Double num = InputBox("Enter numerator:") den = InputBox("Enter denominator:") result = num / den MsgBox "Result: " & result Exit Sub ErrorHandler: MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical End Sub
Exit Sub before the error handler label! Without it, the error handler code runs even when there's no error.On Error Resume Next
VBA Sub ConvertTextToNumbers() Dim cell As Range On Error Resume Next ' Skip cells that can't convert For Each cell In Range("A2:A100") cell.Value = CDbl(cell.Value) If Err.Number <> 0 Then cell.Interior.Color = vbYellow ' Flag problem cells Err.Clear End If Next cell On Error GoTo 0 ' Reset error handling End Sub
Err Object
| Property/Method | Description |
|---|---|
Err.Number | Error number (0 = no error) |
Err.Description | Human-readable error message |
Err.Source | Object/application that raised the error |
Err.Clear | Resets Err to no-error state |
Err.Raise | Trigger a custom error |
Debugging Tools
| Tool | Shortcut | Purpose |
|---|---|---|
| Step Into | F8 | Execute one line at a time |
| Step Over | Shift+F8 | Execute Sub call without stepping into it |
| Breakpoint | F9 | Pause execution at a specific line |
| Immediate Window | Ctrl+G | Test expressions, run Debug.Print |
| Watch Window | Debug â Add Watch | Monitor variable values live |
| Locals Window | View â Locals Window | See all local variables and values |
Debug.Print â Your Best Friend
VBA Sub ProcessWithLogging() Dim i As Long, lastRow As Long lastRow = Cells(Rows.Count, 1).End(xlUp).Row Debug.Print "Processing started. Rows: " & lastRow For i = 2 To lastRow Debug.Print "Row " & i & ": " & Cells(i, 1).Value ' Process each row... Next i Debug.Print "Processing complete!" End Sub
Output appears in the Immediate Window (Ctrl+G). This is essential for debugging loops.
Professional Error Handling Pattern
VBA Sub RobustImport() On Error GoTo ErrorHandler Application.ScreenUpdating = False Dim filePath As String, wb As Workbook filePath = Application.GetOpenFilename("Excel Files (*.xlsx),*.xlsx") If filePath = "False" Then Exit Sub ' User cancelled Set wb = Workbooks.Open(filePath) ' ... process data ... wb.Close SaveChanges:=False CleanUp: Application.ScreenUpdating = True Exit Sub ErrorHandler: MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical Debug.Print Now & " ERROR: " & Err.Number & " - " & Err.Description Resume CleanUp End Sub
Solved Examples (Summary)
Ex 1-3: Safe file open with error handling; Division-by-zero trap; Type mismatch handler for InputBox. Ex 4-6: Sheet-not-found handler with On Error Resume Next; Workbook-already-open detection; Logging errors to a "Log" worksheet. Ex 7-10: Custom error with Err.Raise for invalid GST rates; Multi-file import with per-file error handling (continue on failure); Debug.Print timing for performance testing; Complete cleanup pattern with Application settings restoration.
Practice Exercises
- Write a Sub with error handling that opens a file specified by InputBox. Handle "file not found" gracefully.
- Create a loop that converts text-to-number in column A, flagging and skipping non-numeric cells.
- Add breakpoints and use F8 to step through a For loop. Watch variable values in Locals Window.
- Write an error logger that saves error details (timestamp, error number, description, sub name) to a "Log" sheet.
- Use Debug.Print to track execution flow through an If...ElseIf...Else structure â print which branch executes.
- Create a Sub that deliberately raises error 1004 (Application-defined error) and handles it with a user-friendly message.
MCQ Quiz
On Error GoTo 0 does what?
- Jumps to line 0
- Resets error handling to default
- Clears the error
- Exits the Sub
Err.Clear is used to:
- Delete all errors from the log
- Reset Err.Number to 0
- Fix the error
- Restart the Sub
F8 in VBA Editor does what?
- Runs the entire macro
- Steps through one line at a time
- Opens Immediate Window
- Adds a breakpoint
Where does Debug.Print output appear?
- MsgBox
- A worksheet cell
- Immediate Window
- Status bar
On Error Resume Next will:
- Skip the error and continue with next line
- Retry the error line
- Jump to an error handler
- Exit the procedure
đŧ Interview Q1: What are the risks of On Error Resume Next?
It silently ignores ALL errors, potentially hiding bugs. Data could be corrupted without warning. Best practice: use it only for specific expected errors (like checking if a sheet exists), check Err.Number immediately after the risky line, and reset with On Error GoTo 0 as soon as possible.
đŧ Interview Q2: How would you log errors in a production VBA tool?
Create a dedicated "Error_Log" worksheet. In the error handler, write: timestamp (Now), error number, description, procedure name (passed as string), and the data being processed. Use Cells(Rows.Count, 1).End(xlUp).Row + 1 to append to the log. For critical tools, also export the log to a text file.
đŧ Interview Q3: Explain the Resume keyword variants.
Resume = retry the line that caused the error. Resume Next = skip to the line after the error. Resume LabelName = jump to a specific label (e.g., CleanUp section). The third form is most common in professional code to ensure cleanup runs.
- F8 â Step Into (one line at a time)
- Shift+F8 â Step Over
- F9 â Toggle breakpoint
- Ctrl+G â Immediate Window
- Ctrl+Break â Stop running code
đī¸ Mini Project: Robust Data Import Tool
Build a VBA tool that: (1) Prompts user to select a CSV file using GetOpenFilename, (2) Opens the file and reads data row by row, (3) Validates each row â checks for empty required fields, numeric values, valid dates, (4) Copies valid rows to "Clean_Data" sheet, (5) Logs invalid rows to "Error_Log" sheet with error reason, (6) Shows summary: X rows imported, Y rows had errors, (7) Uses comprehensive On Error GoTo with cleanup, (8) Includes Debug.Print timing for performance analysis.
đ Chapter 42 Summary
- Three error types: compile, runtime, logical
On Error GoTo Labelâ jump to error handlerOn Error Resume Nextâ skip errors (use cautiously)On Error GoTo 0â reset to default error handling- Err.Number, Err.Description for error details
- Debug.Print outputs to Immediate Window for logging
- F8 steps through code; F9 sets breakpoints
- Always include cleanup code (Resume CleanUp pattern)
Report Automation â One-Click Report Generation
đ Automating India's Business Reports
At Tata Motors, the finance team generates 24 monthly reports across 6 divisions. Before VBA automation, this took a team of 4 analysts an entire week. After building a one-click VBA system: all 24 reports generate in 12 minutes, formatted, with charts, and exported as PDFs. Annual savings: âš32 lakh in analyst time alone.
Tata MotorsMaruti SuzukiBajaj Financeđ Learning Objectives
- Automate report generation from raw data to finished output
- Use Workbook_Open for auto-executing code
- Build summary sheets from multiple data sheets
- Auto-format reports and export to PDF
- Create navigation menus with VBA buttons
Workbook_Open Event
Code in the ThisWorkbook module (not a regular module) runs automatically when the file opens:
VBA ' In ThisWorkbook module Private Sub Workbook_Open() Worksheets("Dashboard").Activate MsgBox "Welcome! Report data last updated: " & _ Format(Worksheets("Dashboard").Range("A1").Value, "dd-MMM-yyyy"), _ vbInformation, "Sales Report System" End Sub
Creating Summary from Multiple Sheets
VBA Sub CreateMonthlySummary() On Error GoTo ErrorHandler Application.ScreenUpdating = False Dim ws As Worksheet, summaryWs As Worksheet Dim summaryRow As Long ' Create or clear Summary sheet On Error Resume Next Set summaryWs = Worksheets("Summary") On Error GoTo ErrorHandler If summaryWs Is Nothing Then Set summaryWs = Worksheets.Add summaryWs.Name = "Summary" Else summaryWs.Cells.ClearContents End If ' Headers summaryWs.Range("A1").Value = "Division" summaryWs.Range("B1").Value = "Total Sales (âš)" summaryWs.Range("C1").Value = "Transactions" summaryWs.Range("D1").Value = "Average Sale (âš)" summaryRow = 2 ' Loop through all data sheets For Each ws In ThisWorkbook.Worksheets If ws.Name <> "Summary" And ws.Name <> "Dashboard" Then Dim lastRow As Long lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row summaryWs.Cells(summaryRow, 1).Value = ws.Name summaryWs.Cells(summaryRow, 2).Value = _ Application.WorksheetFunction.Sum(ws.Range("D2:D" & lastRow)) summaryWs.Cells(summaryRow, 3).Value = lastRow - 1 summaryWs.Cells(summaryRow, 4).Value = _ Application.WorksheetFunction.Average(ws.Range("D2:D" & lastRow)) summaryRow = summaryRow + 1 End If Next ws CleanUp: Application.ScreenUpdating = True MsgBox "Summary created with " & (summaryRow - 2) & " divisions.", vbInformation Exit Sub ErrorHandler: MsgBox "Error: " & Err.Description, vbCritical Resume CleanUp End Sub
Auto-Formatting Reports
VBA Sub FormatReport() Dim lastRow As Long, lastCol As Long lastRow = Cells(Rows.Count, 1).End(xlUp).Row lastCol = Cells(1, Columns.Count).End(xlToLeft).Column ' Header formatting With Range(Cells(1, 1), Cells(1, lastCol)) .Font.Bold = True .Font.Size = 12 .Font.Color = vbWhite .Interior.Color = RGB(5, 150, 105) .HorizontalAlignment = xlCenter End With ' Borders for all data With Range(Cells(1, 1), Cells(lastRow, lastCol)).Borders .LineStyle = xlContinuous .Weight = xlThin End With ' Auto-fit columns Columns("A:" & Chr(64 + lastCol)).AutoFit ' Currency format for numeric columns Range(Cells(2, 2), Cells(lastRow, 4)).NumberFormat = "âš#,##0.00" ' Page setup With ActiveSheet.PageSetup .Orientation = xlLandscape .FitToPagesWide = 1 .FitToPagesTall = False .PrintTitleRows = "$1:$1" End With End Sub
Exporting to PDF
VBA Sub ExportToPDF() Dim filePath As String Dim fileName As String fileName = "Sales_Report_" & Format(Date, "yyyy-MM-dd") & ".pdf" filePath = ThisWorkbook.Path & "\" & fileName ActiveSheet.ExportAsFixedFormat _ Type:=xlTypePDF, _ Filename:=filePath, _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ OpenAfterPublish:=True MsgBox "PDF exported to: " & filePath, vbInformation End Sub ' Export ALL sheets to one PDF Sub ExportAllSheetsPDF() Dim filePath As String filePath = ThisWorkbook.Path & "\Full_Report_" & Format(Date, "yyyyMMdd") & ".pdf" ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filePath MsgBox "All sheets exported to PDF!", vbInformation End Sub
Emailing Reports (Outlook Integration Overview)
VBA ' Requires: Tools â References â Microsoft Outlook XX.0 Object Library Sub EmailReport() Dim outlookApp As Object, mail As Object Set outlookApp = CreateObject("Outlook.Application") Set mail = outlookApp.CreateItem(0) With mail .To = "manager@company.com" .Subject = "Monthly Sales Report - " & Format(Date, "MMMM yyyy") .Body = "Dear Sir/Madam," & vbCrLf & vbCrLf & _ "Please find attached the monthly sales report." & vbCrLf & _ "Regards," & vbCrLf & "Finance Team" .Attachments.Add ThisWorkbook.Path & "\Sales_Report.pdf" .Display ' Use .Send to send directly End With End Sub
Creating Navigation Menus
VBA Sub CreateNavigationMenu() Dim ws As Worksheet, btn As Button Dim topPos As Long topPos = 50 For Each ws In ThisWorkbook.Worksheets If ws.Name <> "Menu" Then Set btn = Worksheets("Menu").Buttons.Add(50, topPos, 200, 30) btn.Caption = ws.Name btn.OnAction = "GoToSheet" topPos = topPos + 40 End If Next ws End Sub Sub GoToSheet() Dim sheetName As String sheetName = Application.Caller.Caption Worksheets(sheetName).Activate End Sub
Scheduling Discussion
VBA macros can be triggered automatically using Windows Task Scheduler:
- Create a VBScript (.vbs) that opens the workbook (which triggers Workbook_Open)
- Schedule the .vbs file in Task Scheduler at the desired time (e.g., 6:00 AM daily)
- The macro runs, generates reports, exports PDFs, and closes Excel
This enables fully unattended report generation â reports are ready before employees arrive.
Solved Examples (Summary)
Ex 1-4: Workbook_Open that refreshes pivot table data; Summary sheet builder from 4 regional sheets; Complete report formatter (headers, borders, widths, page setup); PDF export with timestamped filename. Ex 5-8: Multi-sheet PDF export; Email with attachment using Outlook; Navigation menu with colored buttons; Dashboard auto-updater that reads from data sheets. Ex 9-12: Print area setter with header/footer; Backup copy creator (Save As with date); Data consolidator from multiple workbooks; Complete one-click monthly report system.
Practice Exercises
- Write Workbook_Open code that displays a welcome message and navigates to the Dashboard sheet.
- Create a VBA Sub that loops through all sheets and creates a summary table (Sheet Name, Row Count, Column Count).
- Build a complete report formatter: headers, borders, auto-fit, currency format, page setup (landscape, fit to 1 page wide).
- Export the active sheet to PDF with filename format: "ReportName_YYYYMMDD.pdf" in the same folder.
- Create a navigation menu sheet with buttons linking to each worksheet in the workbook.
- Build a "one-click" macro that calls FormatReport, then ExportToPDF, then shows completion message with file path.
MCQ Quiz
Where should Workbook_Open code be placed?
- Module1
- Sheet1 code module
- ThisWorkbook code module
- UserForm
ExportAsFixedFormat Type:=xlTypePDF exports as:
- Word document
- Image
- CSV
Application.ScreenUpdating = False is used to:
- Lock the screen
- Prevent screen flicker and speed up macros
- Hide errors
- Disable user input
To create an Outlook email from VBA, you first need to:
- Install a plugin
- CreateObject("Outlook.Application")
- Import a DLL
- Use Shell command
Which method fits a printed sheet to one page wide?
- PageSetup.Zoom = 100
- PageSetup.FitToPagesWide = 1
- PageSetup.Scale = True
- PageSetup.AutoFit
đŧ Interview Q1: How would you automate a daily report that runs at 6 AM without human intervention?
Create a VBScript (.vbs) file that opens the Excel workbook (Workbook_Open event runs the report generation macro, exports PDF, sends email, and closes). Schedule this .vbs file in Windows Task Scheduler to run daily at 6:00 AM. Ensure error handling logs any issues to a file, and the macro closes Excel even on errors.
đŧ Interview Q2: How do you consolidate data from 12 monthly workbooks into one summary?
Use a loop with Workbooks.Open to open each monthly file, read the summary row/range, copy to the consolidated workbook, then close. Use Dir() function to iterate through files in a folder matching a pattern like "Sales_*.xlsx". Include error handling to skip missing or corrupted files.
đŧ Interview Q3: What Application properties should you disable for faster VBA execution?
Application.ScreenUpdating = False (stop screen redraw), Application.Calculation = xlCalculationManual (stop auto-recalculation), Application.EnableEvents = False (stop event triggers), Application.DisplayAlerts = False (suppress dialogs). Always restore all to default in a CleanUp section.
- Alt+F8 â Run macro dialog
- Ctrl+P â Print / Print Preview
- Ctrl+F2 â Print Preview
đī¸ Mini Project: One-Click Monthly Report Generator
Scenario: An Indian retail company has sales data in sheets: "North", "South", "East", "West" with columns: Date, Product, Category, Amount, Quantity.
Build a complete VBA system that:
- Creates a "Summary" sheet with totals per region (Sales, Transactions, Avg Sale)
- Creates a "Category Analysis" sheet with totals per product category across all regions
- Auto-formats both sheets with professional styling (green headers, borders, currency format)
- Inserts a column chart for regional comparison on the Summary sheet
- Sets page setup (landscape, fit to page, header with company name, footer with date)
- Exports all sheets to a single PDF with timestamped filename
- Shows a completion MsgBox with row counts and PDF file path
- Includes comprehensive error handling and performance optimization
Bonus: Add a Workbook_Open event that shows a dashboard and a "Generate Report" button. Add email sending via Outlook.
đ Chapter 43 Summary
- Workbook_Open in ThisWorkbook auto-runs code on file open
- Loop through Worksheets collection to build summaries
- ExportAsFixedFormat Type:=xlTypePDF exports to PDF
- CreateObject("Outlook.Application") enables email from VBA
- Disable ScreenUpdating, Calculation, EnableEvents for speed
- Always restore Application settings in a CleanUp section
- Task Scheduler + VBScript enables unattended automation
- Navigation menus improve user experience in multi-sheet workbooks
đ Congratulations! You've completed Part IX: Automation with Macros & VBA
7 Chapters âĸ 88+ Solved Examples âĸ 35 MCQs âĸ 21 Interview Questions âĸ 7 Mini Projects
Next: Part X â Advanced Excel Features & Integration â