- Learn
- Computer Science & IT
- Digital Skills
- Data Analysis with Spreadsheets
- Automating Work with Macros
Automating Work with Macros
IntermediateLesson 7 of 7 in Data Analysis with Spreadsheets Course
What you will learn
- Explain what a macro is, judge which spreadsheet tasks are worth automating, and set up Excel and a macro-enabled workbook before you record anything.
- Explain what a macro is and spot tasks worth automatingDescribe what macros and scripts do in a spreadsheet, recognize good and poor candidates for automation, and estimate whether automating a task pays off.
- Set up Excel and save a macro-enabled workbookShow the Developer tab, find the macro commands, choose a file format that keeps macros, and prepare a task before recording it.
- Explain what a macro is and spot tasks worth automating
- Record macros with well-chosen names, shortcuts and storage locations, choose between absolute and relative recording, and run, assign and copy macros between workbooks.
- Record a macro with the macro recorderUse the Record Macro dialog to name a macro, give it a shortcut and choose where it is stored, then record and stop cleanly.
- Choose absolute or relative recordingExplain how the recorder stores cell positions in absolute and relative mode, predict where a macro will act, and pick the right mode for a task.
- Run, assign and copy macros between workbooksRun macros from the Macro dialog, shortcuts, buttons and the ribbon, manage the Personal Macro Workbook, and copy macros from one workbook to another.
- Record a macro with the macro recorder
- Find recorded code in the Visual Basic Editor, read what each line does, tidy and extend it safely, and test and fix it step by step.
- Find your way around the Visual Basic EditorOpen the Visual Basic Editor, locate modules and procedures, and recognize the parts and conventions of VBA code.
- Read what recorded code doesRead recorded VBA line by line using objects, properties and methods, and recognize the extra lines the recorder adds.
- Edit a recorded macro to make it shorter and more flexibleRemove unneeded recorded lines, change values safely, make ranges follow the data, and add simple decisions and repetition the recorder cannot capture.
- Test and fix a macro step by stepTest macros on realistic data, step through code, inspect values, and recognize and fix syntax, run-time and logic errors.
- Find your way around the Visual Basic Editor
- Explain why macros are a security risk, use Excel's macro settings, trusted locations and signatures correctly, and share and maintain macro workbooks responsibly.
- Understand macro risks and choose Trust Center settingsExplain what a malicious macro can do, read Excel's macro warnings, and choose and apply the Trust Center macro settings.
- Handle files from the internet, trusted locations and signed macrosExplain why Office blocks macros in downloaded files, unblock a file you trust, and use trusted locations and digital signatures correctly.
- Share and maintain macro workbooks responsiblyPrepare a macro workbook for other users and computers, document it, and keep it working when files and layouts change.
- Understand macro risks and choose Trust Center settings
- Record and read simple Office Scripts and Google Sheets macros, and choose the right automation tool for a task, its users and its platform.
- Automate Excel with Office ScriptsRecord and read a simple Office Script, and explain where scripts are stored, how they are shared and run, and how they differ from VBA.
- Record macros and write Apps Script in Google SheetsRecord, run and edit a macro in Google Sheets, read the Apps Script it creates, and explain authorization, triggers and limits.
- Choose the right automation tool for a taskCompare VBA, Office Scripts and Apps Script on platform, storage, security, triggers and sharing, and pick a suitable tool, or no code at all, for a given situation.
- Automate Excel with Office Scripts
Automating Work with Macros study guide
1Choose a useful task and prepare Excel
A useful automation starts with a stable task and a clear result. You will compare repeated work with the time needed to build, check, and maintain a macro, then look for built-in features that may already solve the problem. Before recording, prepare desktop Excel, choose a file format that keeps the code, and rehearse the actions so the recorder captures a clean sequence. These choices determine what you can safely reuse later.
1.1 Tasks that are worth automating
A macro is a stored sequence of commands that a spreadsheet program can replay. In desktop Excel, the commands use VBA, short for Visual Basic for Applications. The macro recorder writes that code while you work. You can therefore begin with familiar actions, such as selecting a header and applying a fill color.
From actions to a reusable procedure
Each macro is a procedure, a block beginning with a name such as Sub FormatHeader() and ending with End Sub. A module holds procedures in the workbook's VBA project. When you run the macro, Excel follows its commands in order. A recording does not infer a rule like "skip canceled orders" from what you clicked; a decision needs a test added to the code.
Other spreadsheet platforms also have recorders. Office Scripts use TypeScript in supported versions of Excel, including Excel on the web. Google Sheets macros use JavaScript through Google Apps Script. The shared idea is to record actions, inspect the result, and replay a tested process.
Judge the task before building it
Good candidates repeat often, have clear rules, and receive data in a stable layout. Formatting a weekly sales export or removing the same three unused columns from a daily download fits that pattern. The task's consistency matters: a macro that deletes column C will still delete column C after someone moves important data there.
Human judgments, one-time work, and files whose layout changes on every run are poor candidates for a recording. A checklist can be easier to maintain when a person must decide what the next action should be. Automation also needs an owner who can update it when the process changes.
Work out the time saved
A daily report takes 12 minutes by hand. At 5 days a week for 48 working weeks, that is 240 runs, totaling 2,880 minutes, or 48 hours. Building and testing the macro takes 4 hours, or 240 minutes. Starting and checking each automated run takes 1 minute, so each run saves 11 minutes.
The break-even calculation is:
Round up to 22 runs: part of a run cannot repay the remaining setup time. That is about four and a half working weeks. First-year savings are:
Include checking time; the macro's execution time alone understates the work. A 20-minute task done twice a year costs only 40 minutes annually. Even a macro needing no time per run would take 4.5 years to repay 180 minutes of development.
Check for a built-in solution
Before recording, match the need to an existing feature:
- A formula in an Excel table extends with new rows.
- Conditional formatting applies colors by rule; data validation controls entries.
- A
.xltxtemplate supplies the same starting layout. - Power Query repeats import and cleanup steps; a PivotTable repeats a summary when refreshed.
These choices avoid code maintenance and macro warnings. Use a macro when a repeatable sequence still needs automation after this check. Record its input layout and purpose so another person can understand the process.
Key Takeaways
- A macro replays stored commands; its recorder writes VBA from your actions.
- Stable layouts and clear, repeated rules make good automation candidates.
- Break-even runs equal setup time divided by time saved per run, rounded up.
- Include checking and maintenance when judging the benefit.
- Check formulas, tables, templates, and Refresh before choosing code.
1.2 Prepare the workbook before recording
Desktop Excel provides the recorder, the macro list, and the VBA editor. Set up these tools before you record, then choose a file format that can keep the code.
Show the macro commands
In Excel for Windows, choose File > Options > Customize Ribbon, check Developer under the main tabs, and select OK. On a Mac, use Excel > Settings > Ribbon & Toolbar, check Developer, and save. Older Mac versions call Settings "Preferences."
The Developer tab's Code group contains Visual Basic, Macros, Record Macro, Use Relative References, and Macro Security. View > Macros also offers recording, viewing macros, and relative recording. Windows Excel has a small recording button at the left of the status bar.
Keep code in a suitable format
An ordinary .xlsx workbook cannot store VBA. Choose the format for the file's purpose:
| Format | Purpose |
|---|---|
.xlsm | A normal workbook that also holds macros |
.xlsb | A binary workbook that can hold macros |
.xltm | A reusable macro-enabled template |
.xlam | An Excel add-in that provides reusable features |
.xls | An older workbook format that can hold macros |
For most new macro workbooks, use .xlsm. Changing the extension by typing a new name is not the same as selecting the format in Save As.
Suppose "Weekly-Report.xlsx" needs a macro. Choose File > Save As, keep the base name, select Excel Macro-Enabled Workbook (*.xlsm) under Save as type, and save. You now have "Weekly-Report.xlsm". The original .xlsx remains, so an old shortcut can still open the macro-free file. Check the title bar before adding code.
If you save a workbook containing VBA as .xlsx, Excel warns that the VBA project cannot be saved in that format. Choose No and change the file type to .xlsm. Accepting the macro-free format removes the code from the saved file; after closing it, that saved copy has no macros to recover.
Rehearse a small, clear task
Write a short action list before recording. For a header-formatting macro, it might be "select A1:E1, apply bold, apply blue fill, fit columns A:E, finish at A2." Decide which worksheet and cell should be active at the start. Close unrelated workbooks and rehearse the sequence once.
The recorder captures unnecessary clicks, mistaken entries, and their corrections as well as useful actions. Rehearsal reduces the code you will later have to read. Starting with a small task also makes it easier to check whether each recorded action produced the expected result.
Test new or edited macros on a copy of your data: macro changes cannot be reversed with Undo. Keep a saved original available before a first run.
Recognize the browser boundary
Excel on the web can open and edit a macro-enabled workbook while preserving its VBA, but it cannot record, edit, or run that VBA. Open the file in desktop Excel for those actions. Browser automation uses Office Scripts, which has a separate recorder and language.
Key Takeaways
- Show Developer to reach the recorder, macro list, editor, and security controls.
- Save a new macro workbook as .xlsm; .xlsx cannot keep VBA.
- Save As creates a separate file, so check which copy you are using.
- Rehearse the actions and select the intended starting sheet and cell before recording.
2Record macros that run in the right place
The recorder turns your actions into commands, including the cell movements between actions. Naming and storing a macro makes it easy to find; choosing fixed or relative movement makes it work in the intended place. You will record a short formatting task, predict how a recording behaves from a different starting cell, and give people clear ways to run it. You will also move reusable code into the workbook that needs to carry it.
2.1 Record a clear sequence of actions
Start with a rehearsed task and the intended workbook open. The Record Macro dialog sets the macro's identity and storage before Excel begins capturing your actions.
Fill in the recording dialog
Choose Developer > Record Macro, or View > Macros > Record Macro. Give the macro a useful name. It must begin with a letter and use only letters, digits, or underscores after that. Spaces and hyphens are invalid. Avoid cell-reference names: "Q1" is a cell address, and even "TAX2026" refers to a cell because TAX is column 13,570, within Excel's 16,384 columns ending at XFD. "FormatReport" and "Clean_Export" describe actions clearly.
A shortcut uses Ctrl plus a letter on Windows. Entering lowercase "r" assigns Ctrl+R; uppercase "R" assigns Ctrl+Shift+R. Digits and symbols are not accepted. An assigned macro shortcut takes over the same Excel shortcut while its workbook is open. Ctrl+C would interfere with copying; Ctrl+Z would interfere with Undo. Ctrl+Shift combinations clash less often, but check them too: Ctrl+Shift+L already controls filters.
Choose where the code belongs
| Store macro in | What happens |
|---|---|
| This Workbook | Code travels inside the current macro-enabled workbook |
| New Workbook | Code is placed in a separate new workbook |
| Personal Macro Workbook | Code is kept in hidden PERSONAL.XLSB for use across workbooks on this computer |
Choose This Workbook for a report tool that colleagues will receive. PERSONAL.XLSB is useful for your own reusable formatting tools, but sending a report does not send that separate file's code.
Add a description such as "Bold and fill the header row, then fit the columns." It appears when the macro is selected in the Macro dialog and is also copied into the code as a comment. The description should tell a future user what the macro changes.
Record a header-formatting macro
For a report whose headers occupy A1:E1:
- Name the macro "FormatHeader," enter uppercase "H" for Ctrl+Shift+H, choose This Workbook, and add the description.
- Select OK to start recording.
- Select A1:E1, apply Bold, and choose a light blue fill.
- Select columns A:E and double-click a column boundary to fit their widths.
- Select A2, then choose Developer > Stop Recording.
Excel records commands for selections, entries, formatting, sorting, filtering, inserted rows, and many ribbon actions. Pauses and the path of the mouse are not recorded. A decision such as "format only negative totals" needs code added after recording.
Check that recording has stopped
The status bar shows a stop button while recording is active. If you forget to stop, later actions, including actions in another workbook, may enter the same procedure. End the recording before inspecting the result or starting another task.
A fixed range remains fixed. If you recorded A2:E50, next week's rows below 50 will be missed. That is a reason to inspect the code and choose an appropriate range, not a reason to repeat the recording for every new row count.
Key Takeaways
- Macro names start with a letter and cannot contain spaces, punctuation, or a cell-reference name.
- A macro shortcut can replace an existing Excel command while its workbook is open.
- Use This Workbook when the code must travel with the report.
- PERSONAL.XLSB supplies personal tools across workbooks on one computer.
- Descriptions explain the task in the macro list and in code comments.
- Stop recording before doing anything that should not enter the macro.
2.2 Fixed cells and movement from the active cell
A macro can always visit the same cell, or it can move from the cell where you start it. Absolute recording stores fixed selections. Relative recording stores movements from the active cell. These choices govern recorded selections; formula references have their own rules.
Read a recorded selection
The default absolute mode can produce Range("C3").Select. On every run, this line selects C3, regardless of the previously active cell.
Turn on Use Relative References before or during recording to store relative movements. A line such as ActiveCell.Offset(1, 0).Range("A1").Select moves one row down in the same column. In Offset(rows, columns), positive rows move down and negative rows move up; positive columns move right and negative columns move left. Offset(0, 2) moves two columns right. The recorder's final .Range("A1") means the single cell at the offset position, not worksheet cell A1.
The button is a toggle and looks highlighted when on. Switching it during a recording changes how later selections are recorded. A macro can therefore jump to a fixed starting point, then use relative movements.
Predict a run from a new starting cell
Select C2 before starting a recording. Type "Done" and press Enter. The entry is recorded as ActiveCell.FormulaR1C1 = "Done" in either mode. The movement afterward differs:
| Recording mode | Movement line | Run starting at C7 |
|---|---|---|
| Absolute | Range("C3").Select | Writes "Done" in C7, then selects C3 |
| Relative | ActiveCell.Offset(1, 0).Range("A1").Select | Writes "Done" in C7, then selects C8 |
Absolute mode does not turn an ActiveCell entry into a fixed destination. Read the actual commands. Clicking C2 after recording begins would add a selection that could force the macro back to C2.
Keep formula references separate
When you type a formula, Excel records it in R1C1 notation. R means row and C means column. Numbers in square brackets are offsets from the formula cell; numbers without them are fixed row or column numbers.
Typing =SUM(B2:B13) in B14 becomes =SUM(R[-12]C:R[-1]C): from 12 rows above through 1 row above in the same column. Typing =SUM($B$2:$B$13) becomes =SUM(R2C2:R13C2): fixed rows 2–13 in column 2. The dollar signs in the typed formula decide this distinction. The relative-recording toggle does not change them.
Match the mode to the task
Choose absolute selections for a fixed title or header. Choose relative movements to format the current row or mark the next log entry. A relative macro still needs the correct starting position: starting in the middle of a row shifts all later work.
Google Sheets offers the same selection choice when recording: absolute references use the recorded cells; relative references work from the cell selected before the run.
Key Takeaways
- Absolute recording stores selected addresses; relative recording stores cell movements.
- Offset takes rows first and columns second.
- Select the starting cell before recording to keep that click out of the macro.
- The recording toggle governs selections; dollar signs govern typed formula references.
- Read ActiveCell statements separately from fixed Range statements.
- A relative macro must start in the intended position.
2.3 Run, assign, and move reusable macros
A recorded macro can be started from a list, a shortcut, or a visible button. Before running it, check which workbook owns the code and which sheet the commands will change.
Find the macro you need
Press Alt+F8, or choose Developer > Macros. The Macros in list filters to All Open Workbooks, This Workbook, or a named workbook. Select a macro and choose Run. The dialog also offers Step Into, Edit, Create, Delete, and Options; Options changes its shortcut and description.
A name such as "PERSONAL.XLSB!FormatHeader" identifies a macro in the Personal Macro Workbook. The prefix names the code's owner, not necessarily the workbook that the code will change. Commands using ActiveSheet, ActiveCell, or unqualified ranges still depend on the active context.
Put a start control where users can find it
Choose Developer > Insert > Form Controls > Button, draw the button on the sheet, and choose the procedure in Assign Macro. Right-click the button to edit its label or assign a different macro. A shape or picture can also start a macro through its right-click Assign Macro command.
For a toolbar or ribbon control, open File > Options > Quick Access Toolbar or Customize Ribbon. Set Choose commands from to Macros, select the macro, and add it. These controls provide convenient access, but they do not move code into a workbook.
Protect the test data
Macro changes cannot be reversed with Ctrl+Z, and running a macro clears the normal Undo history. Use a separate test copy. With AutoSave on, a OneDrive or SharePoint file saves changes continuously; closing without saving will not roll them back. Turn AutoSave off before a test run. If changes have already been saved, restore a backup or use File > Info > Version History.
Manage the Personal Macro Workbook
Excel creates PERSONAL.XLSB the first time you choose it as the recording destination. It lives in the XLSTART folder, opens with Excel, and is normally hidden. View > Unhide makes it visible. When quitting after changing its code, save the Personal Macro Workbook when prompted.
To delete an ordinary macro, select it in the Macro dialog and choose Delete. For a personal macro, first unhide PERSONAL.XLSB, or remove the procedure in the VBA editor.
Copy code for another workbook
Open both workbooks and press Alt+F11. In Project Explorer, drag the required standard module from its source VBAProject to the receiving project. Excel copies the whole module, which may contain several procedures. Alternatively, export the module to a .bas file and import it into the receiving project. Save the receiving workbook as .xlsm, then check its button assignments and any sheet names in the copied code.
An opening event is different from a normal button macro. A Workbook_Open procedure placed in ThisWorkbook runs when the file opens with macros enabled. It can display an Instructions sheet, but the event code belongs in that workbook module, not in a standard module copied for ordinary macros.
Key Takeaways
- Alt+F8 lists macros in open workbooks; the file prefix identifies where code is stored.
- Form Control buttons and shapes can start assigned macros.
- Test copies and version history protect data when Undo cannot restore macro changes.
- Save PERSONAL.XLSB after adding or changing personal macros.
- Dragging a standard module between projects copies every procedure in it.
- Workbook_Open belongs in ThisWorkbook and needs macros enabled.
3Read the code, improve it, and test the result
Recorded code becomes easier to use when you can explain what each line changes. You will find procedures in the editor, read Excel objects and their settings, and replace unnecessary selections with direct commands. Then you will make a range follow the data and add a small decision and loop. Testing comes with each edit: stepping through code and checking known results lets you locate both visible errors and mistakes that finish without a warning.
3.1 Find procedures in the VBA editor
The Visual Basic Editor, or VBE, is a separate window for viewing and editing VBA. On Windows, Alt+F11 switches between Excel and the editor. You can also choose Developer > Visual Basic, or select a macro in the Macro dialog and choose Edit.
Locate the right code
Project Explorer lists open workbooks as projects, such as "VBAProject (Weekly-Report.xlsm)." Press Ctrl+R to show it. Expand the project belonging to your workbook before opening a module; two projects can both contain a "Module1."
Within a project, Microsoft Excel Objects holds a module for each sheet and one called ThisWorkbook. These hold code tied to those objects, including workbook events. Recorded macros normally appear under Modules in a standard module. Several procedures can share that module, and later recording sessions may add Module2 or another module.
Double-click a module to open its code window. The Properties window, opened with F4, shows settings for the selected item. Ctrl+G opens the Immediate window, where you can run a single command or inspect test output.
Read the procedure boundaries
A simple macro has this shape:
Sub FormatHeader()
' Make the header easier to read
Range("A1:E1").Font.Bold = True
End Sub
Sub FormatHeader() begins the procedure and supplies its name. End Sub closes it. The empty parentheses mean there are no arguments to supply. Public, argument-free procedures in standard modules can appear in the Macro dialog. Procedures needing arguments and procedures marked Private do not appear there.
The apostrophe starts a comment. Excel ignores that text when the code runs, so comments can explain a purpose or a required layout without becoming commands. Write a comment that adds meaning, such as "Row 1 contains the export headers," where that assumption matters.
Recognize the editor's signals
The editor normally shows keywords such as Sub, With, and End in blue and comments in green. Other code is black. A line with invalid syntax turns red. Colors help you spot structure; they do not establish that the macro does the right work.
VBA keywords and Excel object names stay English in every language version of Excel. Code uses Range, If, and Worksheets even when the ribbon uses another language. A formula written with the Formula property also uses English function names, such as SUM.
A long command can continue on another line if the previous line ends with a space and an underscore: _. This continuation keeps one statement together; it does not begin a new command. The recorder often uses it in long sorting instructions.
Save changes and catch variable typos
Ctrl+S in the editor saves the workbook containing the code. Closing the editor alone does not save it. Keep that workbook in a format that retains VBA.
Place Option Explicit at the top of a module to require variable declarations. For example, if you declare lastRow and later mistype it as lastRwo, VBA can flag the undefined name. Tools > Options > Require Variable Declaration adds Option Explicit to new modules. It does not add declarations to existing procedures for you.
Key Takeaways
- Project Explorer groups code by workbook; open the intended project first.
- Recorded macros live in standard modules, while workbook events use ThisWorkbook.
- Sub and End Sub mark a procedure; an apostrophe starts a comment.
- VBA names stay English across interface languages.
- Ctrl+S saves the workbook, while closing the editor alone does not.
- Option Explicit catches undeclared variables, including misspelled names.
3.2 Read objects, properties, and methods
VBA names the thing to work on, then the setting to change or action to perform. Reading these parts separately turns an unfamiliar line into a short instruction.
Follow the object hierarchy
An object is something Excel exposes to code. Application contains Workbooks; a workbook contains Worksheets; a worksheet contains Ranges. Dots link the levels:
Workbooks("Weekly-Report.xlsm").Worksheets("Report").Range("A1")
This names A1 on Report in a particular open workbook. Leaving out outer levels makes the active context matter. ActiveWorkbook, ActiveSheet, and ActiveCell explicitly refer to what is active at run time. Selection refers to the current selection, which can change while the macro runs.
Separate settings from actions
A property is a value or setting. An equals sign often assigns a new value:
Range("A1").Font.Bold = True
Range("B2").Value = 250
The first sets a font property; the second writes a cell value. A method performs an action, such as Range("A1:E1").Select or Columns("A:E").AutoFit. A method can take arguments. In ActiveWindow.SmallScroll Down:=6, the named argument Down receives 6; the := introduces a named argument, not a property assignment.
Translate recorded formatting
A recorder can produce:
Range("A1:E1").Select
Selection.Font.Bold = True
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 15773696
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Columns("A:E").Select
Columns("A:E").EntireColumn.AutoFit
ActiveWindow.SmallScroll Down:=6
Range("A2").Select
Read it in order: select the header, make it bold, set the selection's fill, fit the columns, scroll down six rows, and finish at A2. A With ... End With block gives several settings to one object. Each leading dot inside it means "on the object named after With." Here that object is the selected cells' Interior, or fill.
The recorder includes settings you may not have meant to change. A fill choice can generate pattern and tint settings along with the color; scrolling adds a command too. Read these lines before removing them. A recorded setting can matter if the cells begin with a different fill.
Decode constants, colors, and cell numbers
Names beginning with xl, such as xlSolid, xlAutomatic, and xlUp, are built-in constants: meaningful names for values Excel recognizes. They are not text strings and do not need quotation marks.
The color number 15773696 represents the same light blue as RGB(0, 176, 240), or #00B0F0. Excel combines the components as red plus 256 times green plus 65,536 times blue. RGB makes a later color change easier to read.
Range("B3") names a cell by address. Cells(3, 2) names the same cell by row 3 and column 2. The row comes first. Numbered cells become useful when a calculation supplies the row for the next action.
Key Takeaways
- Dots connect Excel objects from workbook to sheet to range.
- Properties are settings; methods carry out actions.
- Selection and ActiveCell depend on the state of Excel during the run.
- Leading dots in a With block refer to the object named after With.
- RGB makes a recorded color number readable.
- Cells takes the row number before the column number.
3.3 Make recorded code clearer and more flexible
Save a copy before editing. Make one change at a time and compare its result with the original on test data.
Replace selections with direct commands
These two lines:
Range("A1:E1").Select
Selection.Font.Bold = True
can become Range("A1:E1").Font.Bold = True. The command names its target directly, so the selection can stay where it was. Remove unwanted scroll commands. Remove redundant fill defaults only after checking that they are not needed for the intended result on your starting cells.
A clear header macro can name its sheet throughout:
Sub FormatHeader()
' Report headers are in A1:E1
With Worksheets("Report").Range("A1:E1")
.Font.Bold = True
.Interior.Color = RGB(0, 176, 240)
End With
Worksheets("Report").Columns("A:E").AutoFit
End Sub
It formats Report even when another sheet is active in the same workbook. Worksheets("Report") still refers to the active workbook's collection of sheets; name the workbook too when several open workbooks could be targets. A renamed Report tab causes error 9 until the code matches it again. Keep sheet names, text, and range addresses inside straight double quotes. Changing the color to RGB(221, 235, 247) gives pale blue.
Follow the actual rows
Range("A1").CurrentRegion returns the surrounding block bounded by entirely blank rows and columns. A blank row can therefore split data you intended to treat as one block.
Another approach finds the last filled cell in a dependable key column:
Dim lastRow As Long
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Dim declares a variable; Long stores a whole number. Start at the bottom of column A, move up to its last filled cell, and read the row number. If the last data row is 58, Range("A2:E" & lastRow) means A2:E58. With headers in row 1, that is 57 data rows. Use a column that is filled through the final record; another column's extra entries are not discovered by this calculation.
Add a small decision and loop
The recorder cannot infer a rule such as "flag amounts above 1,000." The following macro assumes order IDs in A and numeric amounts in D, with at least one order:
Sub FlagLargeOrders()
Dim lastRow As Long
Dim cell As Range
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
For Each cell In Range("D2:D" & lastRow)
If cell.Value > 1000 Then
cell.Interior.Color = RGB(255, 199, 206)
End If
Next cell
MsgBox "Checked " & (lastRow - 1) & " orders."
End Sub
cell holds one cell at a time. For Each ... Next visits every cell in the range. If ... Then ... End If colors only values above the threshold. & joins text and values in the message; 58 as the last row produces "Checked 57 orders." Conditional formatting can handle this color rule without code; the loop shows how to repeat actions that may later go beyond formatting.
For a destructive action, If MsgBox("Delete last week's rows?", vbYesNo) = vbNo Then Exit Sub stops when the user chooses No. If you rename a procedure, reassign buttons and shapes to its new name and update the comment describing its expected input.
Key Takeaways
- Replace Select/Selection pairs with direct commands and keep settings that affect the result.
- Name the sheet and, when needed, the workbook to control the target.
- CurrentRegion is bounded by blank rows and columns.
- Find the last row in a dependable key column before building a changing range.
- If makes a decision; For Each repeats an action for every cell in a range.
- Renamed procedures need updated button assignments.
3.4 Find the cause when a macro fails
A macro can stop with a message or finish with the wrong result. Test both the code's ability to run and the work it produces. Use a small data set whose correct outcome you can check by hand.
Build tests around likely changes
Try more rows than the recording originally contained, an empty row inside the data, another starting cell, and another active sheet. These reveal fixed ranges, CurrentRegion boundaries, and unwanted dependence on the selection. Record what should change and what should stay untouched before running each test.
A logic error produces the wrong result without an error message. A fixed range that misses newly added records is a logic error even though every line is valid VBA. Compare the result with your expected row count or known totals; successful completion alone is not enough.
Step through the commands
Click inside the procedure and press F8, called Step Into. The yellow highlight marks the next line to run. Each press executes that line and moves the highlight forward. Place Excel and the editor side by side so you can see which cells change. Press F5 to run the remaining code at normal speed.
For a longer procedure, set a breakpoint by clicking the gray margin beside a line or pressing F9. Run with F5. Execution pauses before that line, allowing you to inspect the state just before the action you are investigating.
Inspect values while paused
In break mode, point at a variable to see its value. Open the Immediate window with Ctrl+G, type ? lastRow, and press Enter. You can also inspect ? ActiveSheet.Name to check the current sheet.
Add Debug.Print lastRow temporarily to send a value to the Immediate window during a run. It provides evidence about the range calculation without adding a message box that interrupts every pass through the code.
Distinguish error types
| Error type | What you observe | Example to check |
|---|---|---|
| Syntax | A malformed line turns red | A missing closing quote |
| Compile | VBA cannot start or compile the procedure | An undeclared variable under Option Explicit |
| Run-time | Execution stops with a numbered message | A missing sheet or an invalid selection |
| Logic | The run finishes but the output is wrong | New rows outside a fixed range |
Run-time error 9, "Subscript out of range," often means a named worksheet or workbook is absent. If With Worksheets("Report ") fails, choose Debug and compare the string with the tab name "Report." The trailing space makes it a different name. Correct the string and continue with F5, or reset before beginning a fresh run.
Run-time error 1004 means Excel could not perform an action on the object. For example, selecting A1 on Data while another sheet is active can fail. Directly setting Worksheets("Data").Range("A1").Value avoids the need to select that sheet's cells.
Finish or reset the test
A paused procedure leaves Excel in break mode. Finish it or choose Run > Reset, the square button, before starting another macro. Esc or Ctrl+Break can interrupt a procedure that runs too long. After fixing an error, rerun the relevant test from a clean starting copy so partially completed actions do not hide another problem.
Key Takeaways
- Use known results and changed inputs to detect logic errors.
- F8 executes one line; yellow marks the next line to run.
- F9 sets a breakpoint, and F5 runs or continues the procedure.
- Inspect variables and the active sheet in the Immediate window.
- Check names for error 9 and invalid object actions for error 1004.
- Finish or reset a paused procedure before starting a fresh test.
4Trust, share, and maintain macro workbooks
A macro workbook combines data with code that can act using your access rights. Choosing whether to run that code requires more than recognizing a familiar filename. You will distinguish ordinary disabled-macro warnings from Windows internet blocks, see what a trusted folder or signature changes, and prepare a workbook for colleagues. Clear instructions, tested layouts, and recoverable versions help the tool remain useful when its original author is away.
4.1 Understand warnings and Trust Center settings
VBA runs with the rights available to Excel and the signed-in user. That access can include reading, changing, or deleting files and starting programs. A malicious macro can therefore harm more than the workbook that contains it. Attackers often disguise macro files as invoices, delivery notices, or salary information.
Find the controls
In Excel for Windows, open File > Options > Trust Center > Trust Center Settings > Macro Settings. Developer > Macro Security opens the same settings page. An organization can manage these controls by policy; grayed-out options are a sign that local choices may be restricted.
The four main VBA settings serve different purposes:
| Setting | Behavior |
|---|---|
| Disable without notification | Macros are disabled without a message; trusted locations are an exception |
| Disable with notification | Macros are disabled, with a notice that may allow a trust decision |
| Disable except digitally signed macros | Trusted signed projects can run; unsigned projects are disabled |
| Enable VBA macros | Allows macros broadly, subject to separate internet blocking and organizational policy |
Disable VBA macros with notification is the usual default. The "Enable VBA macros" setting removes a major safeguard and is labeled not recommended. Antivirus software does not make every macro trustworthy.
Read a normal disabled-macro warning
A workbook subject to the normal notification setting may display a yellow Security Warning saying that macros have been disabled, with an Enable Content button. Enabling active content can allow opening code to execute, so assess the file before clicking.
Ask whether you expected the file, know its sender, and have a clear reason it needs macros. If any answer is unclear, leave macros disabled and verify the request through another channel, such as a phone call. A message telling you to enable content just to view an ordinary invoice is a warning sign: reading that invoice should not require running code.
After you enable content, Excel commonly remembers the file as a trusted document. It may then open without the same warning. Trust Center > Trusted Documents can clear previously trusted documents. Trusting one file differs from allowing all macros through the global setting.
Leave specialized access controls alone unless needed
Trust access to the VBA project object model lets software work with the VBA project's code itself. It is off by default. Ordinary recorded macros do not require it, so leave it off unless a trusted tool specifically needs to change VBA code automatically.
Enable Excel 4.0 macros when VBA macros are enabled concerns the older XLM macro system. It extends the VBA setting to that older technology; it is not needed merely because a workbook contains an ordinary recorded VBA procedure.
A Windows internet block is separate from the normal yellow notice. A downloaded file can remain blocked even when a broad macro setting would otherwise allow its code. Use the warning's actual behavior to identify the trust decision being requested.
Key Takeaways
- VBA can act with your file and program access rights.
- The default notification setting disables macros while allowing a file-specific trust decision.
- Verify the source and purpose before enabling content.
- Trusted-document status remembers a decision about an individual file.
- Ordinary recorded macros do not need access to the VBA project object model.
4.2 Downloaded files, trusted folders, and signatures
Windows marks many browser downloads and saved email attachments as coming from the internet. This Mark of the Web affects how desktop Office handles macros, even when the file's contents look familiar.
Recognize the internet block
Office on Windows blocks internet-origin macros by default. In Microsoft 365 Current Channel, the change began with version 2206, rolling out from July 2022. The red Security Risk bar says the source is untrusted and offers Learn More, without an Enable Content button. It represents a different state from the ordinary yellow disabled-macro warning.
After verifying an expected file's source and purpose, close it. In File Explorer, right-click the file, choose Properties, check Unblock on General, and select OK. Reopen it. Removing the internet marker returns it to the normal macro-setting checks; it does not establish that the code is harmless or override company policy.
A browser download from SharePoint or OneDrive can receive the marker. Opening with Open in Desktop App, or using the synced OneDrive copy, avoids that download path. The method used to open a file matters as well as where the team stores it.
Keep trusted locations narrow
A trusted location is a folder whose files bypass many Office security checks and can open with macros enabled. Add one under Trust Center > Trusted Locations > Add new location. Use a tightly controlled folder with limited write access. Downloads and Desktop collect files from too many sources to be good choices.
Network trusted locations require an additional setting labeled not recommended. A trusted folder is a continuing permission for files placed there, so everyone who can write into it affects what code may be allowed to run.
Understand what a signature establishes
A VBA digital signature identifies the publisher and supports checking that the code has not changed since signing. In the editor, a developer uses Tools > Digital Signature with a code-signing certificate. Editing the code invalidates its existing signature and requires signing again before distributing the revised project.
A trusted publisher's signed macros can run under Disable VBA macros except digitally signed macros. A signature from a publisher not yet trusted brings a trust notice; unsigned macros are disabled without that notice. A signature establishes identity and code integrity, not that the publisher's code is suitable for every use.
For an internet-origin file, Office evaluates trusted locations, trusted-publisher signatures, organizational macro policy, and earlier trusted-document status before applying the default block where no trust path applies. Policy may still prevent a user from changing the outcome.
Apply the checks to a received tool
A colleague sends "Budget-Tool.xlsm," which opens with a red bar. Confirm the sender's request independently, then use Properties to unblock the verified copy if organizational policy allows it. Reopen and handle any normal notification. For an ongoing team process, a controlled SharePoint copy opened in desktop Excel avoids distributing many independently unblocked attachments.
This automatic Windows internet block is not the Mac behavior. Excel on the web and mobile apps do not run VBA at all; removing a Windows marker does not give them that capability.
Key Takeaways
- The red Windows internet block has no Enable Content button.
- Unblocking a verified file removes the internet marker; normal settings and policy still apply.
- A trusted location permits code from files placed there, so control who can write into it.
- A signature identifies a publisher and detects code changes after signing.
- Editing signed VBA requires signing the revised project again.
- Open in Desktop App and browser download can produce different trust behavior.
4.3 Make a macro workbook usable by other people
A macro is ready to share when another person can open the right file, supply the expected data, run the intended procedure, and check the result. The code's location and its written instructions both matter.
Put the code in the shared file
Before sharing, confirm that the procedures live in the workbook's own VBA project. A button assigned to a macro in your PERSONAL.XLSB depends on a separate file on your computer. Copy the required standard module into the report workbook, save it as .xlsm, and assign the button to the procedure in that workbook.
Test from another computer or user account. Desktop Excel for Windows and Mac can run VBA, but Windows-specific features such as ActiveX controls do not work on Mac. Excel on the web and mobile apps cannot run VBA. A file that opens successfully on a colleague's device may still lack a usable way to run its automation.
Many organizations filter .xlsm email attachments. A link to a controlled OneDrive, SharePoint, or Teams file is often more practical. Tell users to open it in desktop Excel when they need the VBA. A link alone does not explain the required application or layout.
Write instructions for the person running it
An Instructions sheet should name:
- What the macro changes and what output to expect.
- How to start it, such as "Click the Format Report button."
- The required input sheet, header row, and column layout.
- Who maintains the tool and how to report a problem.
- The date and version of the last change.
Code comments serve the next person editing it. Describe why a range or condition is used, especially assumptions that are not obvious from the command. An Instructions sheet for users and comments for maintainers solve different needs.
Keep layout changes from breaking the process
A recorded address assumes that data stays in the same place. Inserted columns, moved headers, and renamed sheets can break that assumption. Sheet protection can help preserve a layout. An Excel table or a named range such as Range("SalesData") can give the code a meaningful target that follows many row or column insertions.
These references still need checking after a structural change. For example, a named range may follow inserted rows, while a literal sheet-name string in the same macro still needs updating after a tab is renamed. Test the whole path from input through output.
Keep recoverable versions
Save a dated or numbered copy before a major edit, such as "Report-Tool-v1.2.xlsm," or use OneDrive or SharePoint version history. Record what changed in a short change log on the Instructions sheet. If a new version stops handling an older export correctly, the log helps locate which layout assumption changed.
In the editor, Tools > VBAProject Properties > Protection > Lock project for viewing can deter casual viewing and editing after saving, closing, and reopening. This is weak protection that tools can remove. Keep passwords and other secrets out of VBA code, even in a locked project.
Key Takeaways
- Shared buttons must point to code available in the shared workbook.
- Test on the recipient platform and account.
- An Instructions sheet serves users; code comments serve maintainers.
- Tables and named ranges can reduce dependence on fixed cell positions.
- Keep a recoverable version and record changes.
- A VBA project password is weak protection and cannot secure secrets.
5Choose between desktop and cloud automation
The place where people work shapes which automation they can use. Desktop VBA, Office Scripts, and Google Apps Script have different languages, code storage, permissions, and ways to start a run. You will read small examples from the cloud tools and connect their storage and trigger choices to practical team needs. A useful choice also considers licensing, the person who will maintain the code, and whether a built-in spreadsheet feature already handles the task.
5.1 Record and share an Office Script
Office Scripts automate Excel with TypeScript, which adds data types to JavaScript. Use the Automate tab in Excel on the web, Excel for Windows version 2210 or later, or Excel for Mac.
Check access and make a recording
Work and school use requires a supported Microsoft 365 license, OneDrive for Business, and an internet connection with connected experiences available. Administrators can disable Office Scripts. Personal and family subscriptions have preview access. A missing Automate tab calls for checking these requirements and organizational settings.
Choose Automate > Record Actions, perform a small task, then select Stop. The Action Recorder lists the steps and saves the new script. Run it again from Automate. Copy as code lets you take recorded steps into code without saving them as a whole script.
Read the code's targets and settings
A header-formatting script has this shape:
function main(workbook: ExcelScript.Workbook) {
let sheet = workbook.getActiveWorksheet();
let header = sheet.getRange("A1:E1");
header.getFormat().getFont().setBold(true);
header.getFormat().getFill().setColor("#00B0F0");
}
main is the starting function. Excel supplies the workbook object. let creates a variable: sheet receives the active worksheet, and header receives its A1:E1 range. The later lines set bold and a light blue fill, the same color as VBA's RGB(0, 176, 240).
Office Scripts use get and set methods to reach and change settings. For example, VBA's .Font.Bold = True corresponds to .getFormat().getFont().setBold(true). TypeScript uses lowercase true; the example's statements end in semicolons. Both examples target the active sheet, so choose that sheet deliberately when testing.
Separate the code from the workbook
Scripts are .osts files in the creator's OneDrive, normally under Documents > Office Scripts, or in SharePoint. They are not embedded in the workbook. A workbook using Office Scripts can remain .xlsx.
Associate a script with a workbook from its details to share it. Colleagues inside the organization who have edit access and Office Scripts available can view and run the associated script. Read-only access and outside-organization sharing do not provide that ability. A script button on the sheet gives users a visible start control.
A shared script can still depend on its creator's OneDrive account. Put team-owned scripts in SharePoint to avoid losing access when that account is removed.
Start cloud runs and understand access
Office Scripts have no Excel events equivalent to opening a workbook or editing a cell. A person starts a script, or Power Automate calls it on a schedule or in response to a workflow event. A scheduled flow can run even when nobody has the workbook open.
Scripts cannot open local computer files or start desktop programs. They can call external web services with fetch when run from Excel, subject to administrator controls. External calls are unavailable through Power Automate or for scripts stored on SharePoint. The ability to call a service can send workbook data outside the file, so inspect what a shared script does.
VBA covers more desktop Excel features and also automates other Office apps. Moving a VBA process into Office Scripts requires rewriting or re-recording its steps; opening the workbook in a browser does not translate its code.
Key Takeaways
- Office Scripts use TypeScript and the Automate tab on supported Excel platforms.
- The main function receives the workbook; get and set methods read and change its objects.
- Scripts are separate .osts files, so the workbook can remain .xlsx.
- Workbook-associated scripts need eligible colleagues with edit access inside the organization.
- Power Automate supplies scheduled or workflow-triggered runs.
- External web calls are possible from Excel, with restrictions for flows and SharePoint scripts.
5.2 Record and edit a Google Sheets macro
Google Apps Script automates Sheets and other Google Workspace apps using JavaScript. You edit it in a browser, and the code runs on Google's servers. A Sheets macro is a convenient way to create a first function by recording actions.
Record the task
Choose Extensions > Macros > Record macro in Google Sheets. Select Use absolute references for fixed cells or Use relative references for actions based on the starting selection. Perform the steps, choose Save, give the macro a name, and save again.
You can assign a unique shortcut of Ctrl+Alt+Shift plus a digit. Up to 10 macros in one spreadsheet can have shortcuts; additional macros are available from Extensions > Macros.
The recording becomes a JavaScript function in the spreadsheet's bound Apps Script project. A bound project belongs to that spreadsheet and is copied when the spreadsheet is copied. The recorder normally places functions in a script file called macros.gs; the project's manifest connects menu names and shortcuts to functions.
Read a short formatting function
A recording can select the header before formatting it:
function FormatHeader() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange("A1:E1").activate();
spreadsheet.getActiveRangeList().setFontWeight("bold")
.setBackground("#00b0f0");
}
function begins a named block of work, and var creates a variable for the active spreadsheet. getRange locates the header, activate selects it, and the following methods apply bold and a light blue background. The dots connect each action to the object it affects.
The same formatting can target the cells directly:
SpreadsheetApp.getActive().getRange("A1:E1")
.setFontWeight("bold").setBackground("#00b0f0");
To edit the recording, choose Extensions > Macros > Manage macros, then Edit script from the macro's menu, or open Extensions > Apps Script. Manage macros also changes names and shortcuts. Import macro adds an existing argument-free function to the macro menu.
Understand permission requests
A run that needs protected data or services asks you to authorize access and lists the requested permissions. Read those permissions before granting access: a script can act on Google data within them. A script that formats a sheet and one that sends Gmail messages need different kinds of access.
Simple triggers have reserved function names such as onOpen and onEdit. They run automatically for supported file actions without an authorization prompt. Because they cannot use services requiring authorization, a simple onEdit cannot send a summary email.
An installable time-driven trigger can run a function on a schedule while the spreadsheet is closed, such as daily within the 7:00–8:00 window. This suits jobs whose timing does not depend on someone opening the file.
Keep each job within limits
A macro or installable-trigger execution has a 6-minute limit. Simple triggers have a 30-second limit. Daily trigger run time is also limited per user: 90 minutes for consumer accounts and 6 hours for Google Workspace accounts. Split large jobs into smaller runs and account for all triggers sharing that allowance.
Google Sheets does not execute VBA inside an .xlsm file. Check imported data and formulas, then rebuild the automation in Apps Script; a file conversion does not translate the macro.
Key Takeaways
- A recorded Sheets macro is a JavaScript function in a spreadsheet-bound project.
- Absolute or relative recording controls where the actions are applied.
- Copying the spreadsheet also copies its bound script.
- Authorization grants access to the Google data and services a script requests.
- Simple triggers cannot use services that require authorization.
- Time-driven triggers run in the cloud, subject to execution and daily limits.
- VBA needs to be rewritten or re-recorded for Google Sheets.
5.3 Match the tool to the people and process
Choose an automation tool by working backward from the task's users, data, and running conditions. Knowing the language alone is not enough: a useful script must also be accessible, maintainable, and able to start when the work requires it.
Start with the task and a built-in option
Ask whether a formula, table, conditional format, Power Query process, or PivotTable refresh already does the job. If so, use that feature. Code adds value when a repeatable sequence still needs it. A process whose rules change every month may be easier to operate with a checklist.
Next, find where the data and users work. Desktop Excel, a Microsoft 365 browser workflow, and Google Sheets provide different homes for automation:
| Feature | VBA | Office Scripts | Apps Script |
|---|---|---|---|
| Language | VBA | TypeScript | JavaScript |
| Runs in | Desktop Excel on Windows or Mac | Supported Excel on web, Windows, or Mac | Google's servers for Google apps |
| Code storage | Macro-enabled workbook or PERSONAL.XLSB | Separate OneDrive or SharePoint script | Bound project for a recorded Sheets macro |
| Automatic starts | Desktop workbook events while Excel is running | Power Automate schedule or workflow | Simple or installable triggers |
| Access | User's desktop rights | Workbook operations; restricted external web calls | Authorized Google services and data |
All three offer recording as a starting point. Excel VBA switches selection recording with Use Relative References; Sheets asks for fixed or relative references; Office Scripts lists actions in the Action Recorder. After recording, read and test the code before making it part of the process.
Decide how the run will start
An analyst formatting the same monthly export in desktop Excel, sometimes offline, can use a VBA macro in the Personal Macro Workbook. That storage makes sense for the analyst's own reusable tool. A shared report would need its code available to the recipients.
A team updating a SharePoint workbook every Monday at 7:00, without anybody opening it, can use an Office Script called by a scheduled Power Automate flow. A Workbook_Open event cannot provide an unattended cloud schedule: it relies on the workbook opening in desktop Excel with macros enabled.
A volunteer group keeping registrations in Google Sheets and sending a daily summary email can use Apps Script with an authorized time-driven trigger. A simple onEdit trigger does not supply the permission needed to send email.
Plan ownership and future changes
Ask who can read and maintain the code. Store a team script where the team can keep access, and write the required input layout and run instructions. Changes to columns, software behavior, permissions, or accounts can break a previously working automation. Keep tests and a recoverable version as part of maintaining it.
Moving platforms preserves the written steps and tested logic, but requires new code. VBA does not execute as an Office Script or in Google Sheets, and Apps Script does not run in Excel. Re-recording the same steps in the destination tool is often a practical way to begin the rewrite.
Key Takeaways
- Choose a built-in spreadsheet feature when it already handles the task.
- Match the automation platform to the users and the data.
- Unattended cloud work needs a cloud trigger or workflow.
- Storage and permissions determine who can keep using the code.
- Maintenance includes layout changes, accounts, tests, and instructions.
- Moving platforms carries over the process, but requires rewritten code.
Automating Work with Macros examples
1Choose a task before recording
12 steps
- 1IntroductionStart with a repeatable result
A weekly export needs the same formatting every time. Before recording a macro (commands Excel replays, written as VBA code), decide whether its layout and rules are stable enough to reuse.
You will estimate the saving, check for a built-in solution, and prepare desktop Excel. These decisions keep the first recording small enough to understand and give you a clear result to test afterward.
- 2ExplanationWhat a recording creates
A macro stores commands that Excel can replay. The recorder writes them in VBA, the language built into desktop Office.
A procedure starts with a line such as
Sub FormatHeader()and ends withEnd Sub. A module holds that procedure in the workbook project. You can start by recording familiar actions before learning to edit their code. - 3AnalogyA checklist Excel can carry out
Think of a recording like a checklist whose steps Excel can execute. If the recorded instruction selects column C, Excel follows that position on the next run too.
The checklist does not know that a newly inserted column has changed what C contains. Stable input layouts make recordings useful; changing layouts require a code change, a different tool, or a human decision.
- 4ConnectionTry a feature that already repeats the work
A rule that colors overdue dates fits conditional formatting. A repeated import and cleanup may already be a Power Query process you can refresh.
Tables extend formulas, templates preserve starting layouts, and PivotTable Refresh repeats summaries. Use these features when they meet the need; a macro then has to solve only the remaining sequence of actions.
- 5ExampleCalculate the saving per run
A report takes 12 minutes manually. Its macro needs 1 minute to start and check, so each run saves 11 minutes. Building and testing takes 240 minutes.
Divide setup by the per-run saving:
The saving repays setup after 22 complete runs, about four and a half working weeks. Round up because the remaining setup time still matters.
- 6ExampleInclude the whole year
At 5 days a week for 48 weeks, the report runs 240 times. Manual work totals 2,880 minutes, or 48 hours.
The first-year net saving is:
That is 40 hours after setup. A task done only twice a year may never repay a comparable build before its rules change.
- 7ChallengeDoes this smaller job pay off?
A job saves 8 minutes each time after automation and takes 120 minutes to build. It will run only 10 times before being replaced. Does setup pay for itself?
---reveal---
No. Ten runs save 80 minutes, below the 120-minute build cost. The result is 40 extra minutes of work; the job would need 15 runs to break even.
- 8ExplanationOpen the recording controls
In Windows Excel, choose File > Options > Customize Ribbon, check Developer, and select OK. On Mac, use Excel > Settings > Ribbon & Toolbar.
Developer gives you Record Macro, Macros, Visual Basic, Use Relative References, and Macro Security. View > Macros also provides recording commands. Identify these controls before starting the task so searching for them does not enter the recording.
- 9ExampleSave a copy that keeps VBA
"Weekly-Report.xlsx" needs a macro. Choose Save As and select Excel Macro-Enabled Workbook (*.xlsm). The new file keeps the code; the original .xlsx still exists.
Check which copy is open. An old shortcut can still open the original. If Excel warns that a VBA project cannot be saved in a macro-free file, cancel that choice and change the file type.
- 10TipRehearse on a test copy
Write the actions in order, choose the starting sheet and cell, and rehearse once. Close unrelated workbooks. Extra clicks and corrections become recorded commands too.
Use a test copy because Undo cannot reverse macro changes. Desktop Excel is required for recording, editing, and running VBA; the web app can preserve the code while data is edited, but cannot execute it.
- 11ChallengeIs this VBA plan ready to use?
A task will run 30 times, saving 6 minutes per run after checking. Setup takes 60 minutes. The learner plans to deliver the macro in .xlsx for browser use. Is this plan ready?
---reveal---
The time saving is worthwhile: 180 minutes saved minus 60 minutes setup leaves 120 minutes. But the VBA plan needs a macro-enabled format such as .xlsm and desktop Excel for running the code. A positive payoff does not fix the format and platform choices.
- 12RecapPrepare a clear first recording
Before recording, identify the repeated task, check a built-in alternative, and estimate whether the saving repays setup.
Write the action list, open the intended sheet, choose a VBA-capable format, and keep a test copy ready. These are the starting conditions you will use to judge the recording's result.
2Record and run in the intended cells
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow one recording through its next run
- 2ExplanationGive the macro a useful name
- 3ExampleChoose code storage and a shortcut
- 4ExampleCapture just the formatting task
- 5ChallengeWill this macro travel with the report?
- 6ExplanationRead the movement
- 7ExampleSeparate an entry from the next selection
- 8ExampleMake the next movement follow the entry
- 9Key InsightFormula dollar signs have a separate job
- 10ChallengePredict the two destinations
- 11ExplanationChoose a way to start the macro
- 12TipKeep a recoverable test state
- 13ExampleMove a reusable module
- 14ConnectionRecognize code that starts on opening
- 15ChallengeRepair the shared run control
- 16RecapCheck identity, destination, and start state
3Improve recorded code and verify its behavior
21 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn a recording into readable instructions
- 2ExplanationOpen the correct module
- 3ExampleRead a procedure boundary
- 4TipSave code and catch names early
- 5ChallengeWhere did the macro go?
- 6ExplanationName the object before its setting
- 7ExampleTranslate selected-cell commands
- 8ExampleUse a block for one object
- 9ChallengeProperty or action?
- 10ExampleRemove a selection pair
- 11ExplanationChoose a range boundary that fits the data
- 12ExampleBuild the range from the endpoint
- 13ExampleVisit and test each amount
- 14ChallengeFind the missed endpoint
- 15ExplanationWatch the next line execute
- 16ExampleAsk what the code is using
- 17ExplanationUse the error as a clue
- 18ExampleTest a result you already know
- 19ChallengeExplain a silent failure
- 20ChallengeCheck the whole chain
- 21RecapKeep one clear test cycle
4Read trust warnings and prepare a shared tool
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA workbook can carry actions as well as data
- 2ExplanationUnderstand what VBA can access
- 3ExplanationDistinguish the main settings
- 4TipVerify the purpose before enabling content
- 5ChallengeWhat does the invitation establish?
- 6ExplanationRecognize the Windows internet marker
- 7ExampleCompare two paths to the same team file
- 8Key InsightA trusted folder grants continuing access
- 9ExplanationA signature ties identity to a code version
- 10ChallengeWhy is the unblocked file still disabled?
- 11ExplanationPrepare the file for the next person
- 12TipKeep changes recoverable
- 13ChallengeCheck the handoff and the trust path
- 14RecapKeep trust and usability checks distinct
5Choose a desktop or cloud workflow
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart from where the work happens
- 2ExplanationUse the Automate tab
- 3ExampleRead the Office Script entry point
- 4Key InsightSharing does not embed the script
- 5ConnectionSchedule through a workflow
- 6ChallengeIs the workbook enough to carry the script?
- 7ExplanationRecord a Sheets function
- 8ExampleReach a range and change its format
- 9TipInspect code and requested access
- 10ExplanationChoose a trigger with the right permissions
- 11ExampleSeparate per-run and daily limits
- 12ChallengeCan a simple edit trigger send this summary?
- 13ExplanationAsk the practical questions in order
- 14ExampleMatch an offline desktop task
- 15ExampleMatch an unattended cloud task
- 16Key InsightKeep the process when rewriting code
- 17ChallengeChoose the whole arrangement
- 18RecapMatch the next task to its environment
Automating Work with Macros practice questions
Set 1: Plan, record, and start a reliable macro10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
ActiveCell.Offset(3, -2).Range("A1").Select. If F4 is active before the line, which cell is selected afterward?Show answerHide answer
Question 7 of 10
ActiveCell.FormulaR1C1 = "Ready" followed by Range("D4").Select. When it is run with H9 active, where does the text go and where does the cursor finish?Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
PERSONAL.XLSB!CleanReport. The recipient has desktop Excel but not Nora's personal workbook. What preparation makes the report self-contained?Show answerHide answer
Set 2: Predict references and read recorded code10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
ActiveCell.Offset(-1, 2) when C8 is active?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
=SUM(D4:D9) is typed in D10 while relative selection recording is off. What R1C1 formula represents those typed references?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
"=R[-2]C+R2C1" into ActiveCell and then selects Range("E6"). What formula is entered and which cell is active at the end?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Workbook_Open in Module1, but opening the file with macros enabled does not trigger it. Where should that event procedure go?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Option Explicit and Dim lastRow As Long. A later line uses lastRwo. Why does VBA flag that later name?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
With Worksheets("Inputs").Range("B1:D1"), followed by .Font.Bold = True. What receives the bold setting?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Worksheets("Logs").Range("B2").Value = 8. The other workbook is active. Which cell changes, and what would remove that workbook dependence?Show answerHide answer
Save this lesson to see this answer.
Set 3: Edit flexible ranges and investigate results10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Range("C2").Value = 75?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Selection.Font.Bold = True. What direct command performs the same formatting?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Range("B2:F" & lastRow). How many data rows does that range contain?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
If cell.Value > 700 Then to flag numeric entries. The values are 690, 700, and 715. Which value is flagged?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Range("A1").CurrentRegion and omits the later records. What change fits the full row span?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
If MsgBox("Remove old rows?", vbYesNo) = vbNo Then Exit Sub before its deletion commands. A user chooses No. What runs after that choice?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
lastRow as 63, but the intended sheet's final ID is on row 91. Another sheet is active. The endpoint uses unqualified Cells, and the loop uses unqualified Range. What should be corrected and retested?Show answerHide answer
Save this lesson to see this answer.
Set 4: Debug, trust, and share workbooks10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Range("SalesData"). Rows are inserted above that named range. Why is this reference useful compared with a literal address string?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Worksheets("Archive "), but the visible tab is named "Archive". What edit addresses that mismatch?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Use cloud recorders, permissions, and triggers10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
fetch call fails when Power Automate runs it. What explains that difference?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
onEdit trigger tries to email a registration summary and cannot use the email service. Why?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 6: Diagnose and improve a complete automation plan10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
FormatExport to PrepareExport. Its worksheet button still names FormatExport. Why does the button fail?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Absolute recording
Action Recorder
Active cell
Authorization
Automation maintenance
Automation platform
AutoSave
B
Bound script project
Break mode
Break-even point
Breakpoint
C
Change log
Code-signing certificate
Comment
Compile error
Constant
xlUp as the direction when moving from the bottom of the key column.CurrentRegion
D
Developer tab
Digital signature
F
For Each loop
G
Google Apps Script
I
If statement
cell.Value > 1000 evaluates to True.Immediate window
? ActiveSheet.Name in the Immediate window reveals the sheet currently used by the test.Instructions sheet
J
JavaScript
setFontWeight("bold") to format the selected header.L
Last-row calculation
Logic error
Long
Dim lastRow As Long prepares a suitable variable for an Excel row number.M
Macro
Macro assignment
Macro description
Macro dialog
Macro recorder
Macro security setting
Macro shortcut
Macro-enabled template
Macro-enabled workbook
Macro-free workbook
main function
Mark of the Web
Method
AutoFit method adjusts report column widths to fit their displayed contents.Module export
MsgBox
N
Named range
No-code alternative
O
Object
Office Scripts
Offset
ActiveCell.Offset(-2, 1) refers to E4 because it moves up two rows and right one column.Option Explicit
lastRwo is flagged instead of silently creating a different variable.P
Personal Macro Workbook
Power Automate
Project Explorer
Property
Range("B1").Font.Bold = True changes a property of the font used in B1.Q
Quota
R
R1C1 notation
R[-1]C names the cell one row above the formula in the same column.Relative recording
RGB
RGB(0, 176, 240) to apply the same light blue as hexadecimal color #00B0F0.Run-time error
S
Selection
Selection.Font.Bold statement formats.Simple trigger
Spreadsheet automation
Standard module
Sub procedure
Syntax error
T
Time-driven trigger
Trust Center
Trusted document
Trusted location
Trusted publisher
TypeScript
ExcelScript.Workbook.U
Unattended run
V
Variable
VBA
VBA project lock
VBA project object model access
Version History
Visual Basic Editor
W
With block
.Font.Bold refers to the font of that same header range.Workbook_Open event
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.