Macro
A Macro is an automation tool that records or contains a sequence of commands to perform repetitive tasks automatically. In Excel, macros use VBA (Visual Basic for Applications). In Google Sheets, they use Apps Script (JavaScript).
What Macros Can Do
- Automate repetitive formatting
- Process and transform data
- Generate reports
- Interact with other applications
- Create custom functions
- Build user interfaces
Recording vs Writing Macros
Recording (Easier)
- Turn on macro recorder
- Perform your actions
- Stop recording
- Play back anytime
Pros: No coding required Cons: Limited flexibility, can be inefficient
Writing (More Powerful)
Write code directly in VBA or Apps Script
Pros: Complete control, efficient, conditional logic Cons: Requires programming knowledge
Recording a Macro in Excel
- View → Macros → Record Macro
- Name your macro
- Choose shortcut key (optional)
- Perform your actions
- View → Macros → Stop Recording
Recording a Macro in Google Sheets
- Extensions → Macros → Record macro
- Choose relative or absolute references
- Perform your actions
- Click Save
- Name your macro
Example: VBA Macro
Sub FormatReport()
' Format headers
Range("A1:E1").Font.Bold = True
Range("A1:E1").Interior.Color = RGB(0, 112, 192)
Range("A1:E1").Font.Color = RGB(255, 255, 255)
' Auto-fit columns
Columns("A:E").AutoFit
' Add borders
Range("A1").CurrentRegion.Borders.LineStyle = xlContinuous
End Sub
Example: Apps Script
function formatReport() {
const sheet = SpreadsheetApp.getActiveSheet();
// Format headers
const headers = sheet.getRange("A1:E1");
headers.setFontWeight("bold");
headers.setBackground("#0070C0");
headers.setFontColor("#FFFFFF");
// Auto-resize columns
sheet.autoResizeColumns(1, 5);
}
Running Macros
Excel
- View → Macros → View Macros → Run
- Keyboard shortcut (if assigned)
- Button (from Developer tab)
- Automatically via events
Google Sheets
- Extensions → Macros → [Your macro name]
- Keyboard shortcut
- Custom menu (via script)
- Triggers (time-based or event-based)
Security Considerations
Excel
- Macros can contain malicious code
- Files with macros use .xlsm extension
- Enable only from trusted sources
- Use macro security settings
Google Sheets
- Scripts require authorization
- Review permissions carefully
- Scripts run in Google's cloud
Best Practices
- Comment your code: Explain what each section does
- Use descriptive names:
ProcessMonthlySalesnotMacro1 - Handle errors: Add error handling for robustness
- Test thoroughly: Check edge cases and invalid inputs
- Back up: Save before running new macros
- Modularize: Break complex macros into smaller procedures
When to Use Macros
Good candidates for automation:
- Repeated more than 3 times
- Error-prone manual processes
- Time-consuming formatting
- Regular report generation
Not ideal for:
- One-time tasks
- Simple operations faster done manually
- Tasks requiring human judgment