Automating Work with Macros

Learn to automate repetitive spreadsheet work. Record macros in Excel, choose between absolute and relative recording, and run them from shortcuts, buttons and the ribbon. Read and tidy the VBA code the recorder writes, make it follow your data, and test and fix it step by step. Keep macro-enabled files safe with the right security settings, then compare VBA with Office Scripts and Google Apps Script and decide which tasks are worth automating, and with which tool.

IntermediateLesson 7 of 7 in Data Analysis with Spreadsheets Course

What you will learn

  1. 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 automating
      Describe 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 workbook
      Show the Developer tab, find the macro commands, choose a file format that keeps macros, and prepare a task before recording it.
  2. 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 recorder
      Use 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 recording
      Explain 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 workbooks
      Run macros from the Macro dialog, shortcuts, buttons and the ribbon, manage the Personal Macro Workbook, and copy macros from one workbook to another.
  3. 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 Editor
      Open the Visual Basic Editor, locate modules and procedures, and recognize the parts and conventions of VBA code.
    • Read what recorded code does
      Read 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 flexible
      Remove 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 step
      Test macros on realistic data, step through code, inspect values, and recognize and fix syntax, run-time and logic errors.
  4. 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 settings
      Explain 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 macros
      Explain 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 responsibly
      Prepare a macro workbook for other users and computers, document it, and keep it working when files and layouts change.
  5. 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 Scripts
      Record 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 Sheets
      Record, 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 task
      Compare 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.

Automating Work with Macros study guide

5 chapters

1

Choose 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:

240÷11≈21.8

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:

11×240−240=2400 minutes=40 hours

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 .xltx template 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:

FormatPurpose
.xlsmA normal workbook that also holds macros
.xlsbA binary workbook that can hold macros
.xltmA reusable macro-enabled template
.xlamAn Excel add-in that provides reusable features
.xlsAn 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.
2

Record 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 inWhat happens
This WorkbookCode travels inside the current macro-enabled workbook
New WorkbookCode is placed in a separate new workbook
Personal Macro WorkbookCode 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:

  1. Name the macro "FormatHeader," enter uppercase "H" for Ctrl+Shift+H, choose This Workbook, and add the description.
  2. Select OK to start recording.
  3. Select A1:E1, apply Bold, and choose a light blue fill.
  4. Select columns A:E and double-click a column boundary to fit their widths.
  5. 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 modeMovement lineRun starting at C7
AbsoluteRange("C3").SelectWrites "Done" in C7, then selects C3
RelativeActiveCell.Offset(1, 0).Range("A1").SelectWrites "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.
3

Read 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 typeWhat you observeExample to check
SyntaxA malformed line turns redA missing closing quote
CompileVBA cannot start or compile the procedureAn undeclared variable under Option Explicit
Run-timeExecution stops with a numbered messageA missing sheet or an invalid selection
LogicThe run finishes but the output is wrongNew 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.
4

Trust, 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:

SettingBehavior
Disable without notificationMacros are disabled without a message; trusted locations are an exception
Disable with notificationMacros are disabled, with a notice that may allow a trust decision
Disable except digitally signed macrosTrusted signed projects can run; unsigned projects are disabled
Enable VBA macrosAllows 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.
5

Choose 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:

FeatureVBAOffice ScriptsApps Script
LanguageVBATypeScriptJavaScript
Runs inDesktop Excel on Windows or MacSupported Excel on web, Windows, or MacGoogle's servers for Google apps
Code storageMacro-enabled workbook or PERSONAL.XLSBSeparate OneDrive or SharePoint scriptBound project for a recorded Sheets macro
Automatic startsDesktop workbook events while Excel is runningPower Automate schedule or workflowSimple or installable triggers
AccessUser's desktop rightsWorkbook operations; restricted external web callsAuthorized 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

5 Walkthroughs

1

Choose a task before recording

12 steps
Judge a task, estimate its payoff, and prepare a workbook that can keep the recorded code.
  1. 1
    IntroductionStart 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.

  2. 2
    ExplanationWhat 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 with End Sub. A module holds that procedure in the workbook project. You can start by recording familiar actions before learning to edit their code.

  3. 3
    AnalogyA 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.

  4. 4
    ConnectionTry 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.

  5. 5
    ExampleCalculate 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:

    240÷11≈21.8

    The saving repays setup after 22 complete runs, about four and a half working weeks. Round up because the remaining setup time still matters.

  6. 6
    ExampleInclude 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:

    11×240−240=2400 minutes

    That is 40 hours after setup. A task done only twice a year may never repay a comparable build before its rules change.

  7. 7
    ChallengeDoes 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.

  8. 8
    ExplanationOpen 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.

  9. 9
    ExampleSave 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.

  10. 10
    TipRehearse 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.

  11. 11
    ChallengeIs 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.

  12. 12
    RecapPrepare 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.

2

Record and run in the intended cells

16 steps
Name and store a macro, compare fixed and relative selections, and prepare controls and code for another user.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow one recording through its next run
  2. 2
    ExplanationGive the macro a useful name
  3. 3
    ExampleChoose code storage and a shortcut
  4. 4
    ExampleCapture just the formatting task
  5. 5
    ChallengeWill this macro travel with the report?
  6. 6
    ExplanationRead the movement
  7. 7
    ExampleSeparate an entry from the next selection
  8. 8
    ExampleMake the next movement follow the entry
  9. 9
    Key InsightFormula dollar signs have a separate job
  10. 10
    ChallengePredict the two destinations
  11. 11
    ExplanationChoose a way to start the macro
  12. 12
    TipKeep a recoverable test state
  13. 13
    ExampleMove a reusable module
  14. 14
    ConnectionRecognize code that starts on opening
  15. 15
    ChallengeRepair the shared run control
  16. 16
    RecapCheck identity, destination, and start state
3

Improve recorded code and verify its behavior

21 steps
Read the objects in a recorded procedure, make small edits, and use debugging evidence to check the result.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn a recording into readable instructions
  2. 2
    ExplanationOpen the correct module
  3. 3
    ExampleRead a procedure boundary
  4. 4
    TipSave code and catch names early
  5. 5
    ChallengeWhere did the macro go?
  6. 6
    ExplanationName the object before its setting
  7. 7
    ExampleTranslate selected-cell commands
  8. 8
    ExampleUse a block for one object
  9. 9
    ChallengeProperty or action?
  10. 10
    ExampleRemove a selection pair
  11. 11
    ExplanationChoose a range boundary that fits the data
  12. 12
    ExampleBuild the range from the endpoint
  13. 13
    ExampleVisit and test each amount
  14. 14
    ChallengeFind the missed endpoint
  15. 15
    ExplanationWatch the next line execute
  16. 16
    ExampleAsk what the code is using
  17. 17
    ExplanationUse the error as a clue
  18. 18
    ExampleTest a result you already know
  19. 19
    ChallengeExplain a silent failure
  20. 20
    ChallengeCheck the whole chain
  21. 21
    RecapKeep one clear test cycle
4

Read trust warnings and prepare a shared tool

14 steps
Distinguish trust decisions, handle verified downloads, and keep a shared macro workbook maintainable.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionA workbook can carry actions as well as data
  2. 2
    ExplanationUnderstand what VBA can access
  3. 3
    ExplanationDistinguish the main settings
  4. 4
    TipVerify the purpose before enabling content
  5. 5
    ChallengeWhat does the invitation establish?
  6. 6
    ExplanationRecognize the Windows internet marker
  7. 7
    ExampleCompare two paths to the same team file
  8. 8
    Key InsightA trusted folder grants continuing access
  9. 9
    ExplanationA signature ties identity to a code version
  10. 10
    ChallengeWhy is the unblocked file still disabled?
  11. 11
    ExplanationPrepare the file for the next person
  12. 12
    TipKeep changes recoverable
  13. 13
    ChallengeCheck the handoff and the trust path
  14. 14
    RecapKeep trust and usability checks distinct
5

Choose a desktop or cloud workflow

18 steps
Read Office Scripts and Apps Script examples and match storage, permissions, and triggers to a team task.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart from where the work happens
  2. 2
    ExplanationUse the Automate tab
  3. 3
    ExampleRead the Office Script entry point
  4. 4
    Key InsightSharing does not embed the script
  5. 5
    ConnectionSchedule through a workflow
  6. 6
    ChallengeIs the workbook enough to carry the script?
  7. 7
    ExplanationRecord a Sheets function
  8. 8
    ExampleReach a range and change its format
  9. 9
    TipInspect code and requested access
  10. 10
    ExplanationChoose a trigger with the right permissions
  11. 11
    ExampleSeparate per-run and daily limits
  12. 12
    ChallengeCan a simple edit trigger send this summary?
  13. 13
    ExplanationAsk the practical questions in order
  14. 14
    ExampleMatch an offline desktop task
  15. 15
    ExampleMatch an unattended cloud task
  16. 16
    Key InsightKeep the process when rewriting code
  17. 17
    ChallengeChoose the whole arrangement
  18. 18
    RecapMatch the next task to its environment

Automating Work with Macros practice questions

60 Practice Questions in 6 sets

Set 1: Plan, record, and start a reliable macro10 Practice Questions

Question 1 of 10

A sheet needs to color every overdue date red as entries change. What built-in feature directly fits that need?
  1. A workbook template
  2. Conditional formatting
  3. A PivotTable refresh
  4. A data-validation list
Show answerHide answer
Answer: B
Conditional formatting applies a visual rule to cells and can respond when the dates change. A template can provide a starting layout, but it does not by itself apply a continuing overdue-date test. Choose the feature that performs the required action before adding code.

Question 2 of 10

A weekly task takes 18 minutes manually and 3 minutes to start and check after automation. Development takes 240 minutes. The process will be used for 20 weeks. How much net time will automation save over those weeks?
  1. 120 minutes
  2. 300 minutes
  3. 360 minutes
  4. 60 minutes
Show answerHide answer
Answer: D
Each run saves 15 minutes, so 20 runs save 300 minutes before development is counted. Subtracting the 240-minute build gives 60 minutes of net savings. Reporting 300 minutes overlooks the one-time development cost, even though the run itself is faster.

Question 3 of 10

A workbook contains a new recorded macro and must retain it as an ordinary editable workbook. What usual Save As file type should its owner choose?
  1. Excel Macro-Enabled Workbook (.xlsm)
  2. Excel Workbook (.xlsx)
  3. Excel Template (.xltx)
  4. Comma-delimited text file (.csv)
Show answerHide answer
Answer: A
An .xlsm workbook retains both the spreadsheet and its VBA project. The familiar .xlsx format stores workbook content without retaining VBA, so accepting that format would remove the macro from the saved copy. The macro-enabled file type is the usual choice for a shared report tool.

Question 4 of 10

A macro should be available to its author in many unrelated desktop Excel workbooks on one computer. Where should the author record it?
  1. This Workbook
  2. A new report workbook
  3. Personal Macro Workbook
  4. The Instructions worksheet
Show answerHide answer
Answer: C
The Personal Macro Workbook opens with Excel and supplies personal macros across workbooks on that computer. Storing the macro in This Workbook attaches it to the particular file, so it is available only when that file is open. A worksheet tab is not a separate VBA recording destination.

Question 5 of 10

A report author assigns lowercase "c" as a macro shortcut. While the macro workbook is open on Windows, what happens when the author presses Ctrl+C?
  1. Excel copies the selection.
  2. The macro recorder starts.
  3. The assigned macro runs.
  4. Excel prompts for a choice.
Show answerHide answer
Answer: C
Lowercase "c" assigns Ctrl+C, and the macro shortcut takes over the matching Excel command while its workbook is open. Expecting ordinary copying overlooks that collision. Choose a checked shortcut or another start control so the familiar copy command stays available for normal work.

Question 6 of 10

A macro contains ActiveCell.Offset(3, -2).Range("A1").Select. If F4 is active before the line, which cell is selected afterward?
  1. D7
  2. H7
  3. D1
  4. B3
Show answerHide answer
Answer: A
Offset moves three rows down from row 4 to row 7 and two columns left from F to D, giving D7. H7 comes from treating the negative column argument as a move right. The final Range("A1") identifies the single cell at that offset; it does not reset the destination to worksheet A1.

Question 7 of 10

A recording made with D3 active contains 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?
  1. Text in D3; cursor at D4
  2. Text in H9; cursor at H10
  3. Text in D4; cursor at D4
  4. Text in H9; cursor at D4
Show answerHide answer
Answer: D
ActiveCell writes "Ready" in H9 because that is active when the entry line runs. The separate fixed Range selection then moves the cursor to D4. Finishing at H10 would require a relative one-row-down command, so the fixed recorded address must be read independently of the entry.

Question 8 of 10

A macro must format the same fixed heading cells each time. What recording mode fits the cell selections?
  1. Relative recording
  2. Absolute recording
  3. Either mode with no starting cell
  4. Relative recording after every run
Show answerHide answer
Answer: B
Absolute recording stores the heading cells as fixed selected addresses. Relative recording follows movements from the active cell and can reach a different heading when started elsewhere. The task asks for a fixed destination, so selection addresses should stay tied to that location.

Question 9 of 10

A tester runs a macro on a OneDrive workbook with AutoSave on and then closes the file. The wrong changes remain. What should the tester use to restore an earlier saved state?
  1. The normal Undo command
  2. The Record Macro description
  3. Version History or a backup
  4. The macro shortcut settings
Show answerHide answer
Answer: C
AutoSave can preserve the macro changes before the workbook closes, and normal Undo cannot reverse them. Version History or a backup supplies an earlier saved state to restore. Closing the file is therefore insufficient recovery for this test; a separate test copy prevents damage to the working version.

Question 10 of 10

Nora sends a report with a button assigned to PERSONAL.XLSB!CleanReport. The recipient has desktop Excel but not Nora's personal workbook. What preparation makes the report self-contained?
  1. Copy its module into the report, reassign the button there, and save as .xlsm.
  2. Copy its module into the report, keep the old assignment, and save as .xlsm.
  3. Keep the personal assignment, copy the worksheet button, and save as .xlsm.
  4. Copy its module into the report, reassign the button there, and save as .xlsx.
Show answerHide answer
Answer: A
The recipient needs the procedure inside the report, a button pointing to that procedure, and a file type that retains VBA. Copying the module but leaving the PERSONAL.XLSB assignment still asks Excel to run Nora's separate code. Saving as .xlsx would discard the copied VBA from the saved report.
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

A macro must write "Checked" in the starting cell, then move one row down from that cell on every run. What should the movement after the entry use?
  1. A fixed selection of the recorded next row
  2. A fixed selection of the original starting cell
  3. An Offset(1, 0) relative selection
  4. An Offset(0, 1) relative selection
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What cell lies at ActiveCell.Offset(-1, 2) when C8 is active?
  1. E7
  2. E9
  3. A7
  4. D6
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A formula =SUM(D4:D9) is typed in D10 while relative selection recording is off. What R1C1 formula represents those typed references?
  1. =SUM(R4C4:R9C4)
  2. =SUM(R[-4]C:R[-9]C)
  3. =SUM(R[-6]C4:R[-1]C4)
  4. =SUM(R[-6]C:R[-1]C)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

With E5 active, a macro writes the FormulaR1C1 string "=R[-2]C+R2C1" into ActiveCell and then selects Range("E6"). What formula is entered and which cell is active at the end?
  1. E5 gets =$E$3+A2; E6 is active.
  2. E5 gets =E3+$A$2; E6 is active.
  3. E5 gets =E3+$A$2; E7 is active.
  4. E5 gets =C5+$A$2; E6 is active.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A module contains three macros. What moves when the module is dragged from one workbook project onto another in Project Explorer?
  1. Only the selected macro name
  2. A copy of all three macros
  3. Only the worksheet data
  4. A shortcut to the source module
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A workbook contains Workbook_Open in Module1, but opening the file with macros enabled does not trigger it. Where should that event procedure go?
  1. The ThisWorkbook code module
  2. The first worksheet code module
  3. The PERSONAL.XLSB standard module
  4. A new standard module named Open
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A VBA module contains Option Explicit and Dim lastRow As Long. A later line uses lastRwo. Why does VBA flag that later name?
  1. It cannot hold a row number.
  2. It is missing quotation marks.
  3. It has no variable declaration.
  4. It must begin with a capital letter.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A recorded macro needs to be inspected in the VBA editor. In its workbook project, where should the learner look first?
  1. The worksheet's printed header
  2. The Macro Security settings page
  3. The workbook's named-range list
  4. A standard module under Modules
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A procedure uses With Worksheets("Inputs").Range("B1:D1"), followed by .Font.Bold = True. What receives the bold setting?
  1. The currently selected cells on any sheet
  2. B1:D1 on every open workbook's active sheet
  3. The whole Inputs sheet in the code's workbook
  4. B1:D1 on Inputs in the active workbook
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Two open workbooks both contain a sheet called Logs. A macro in one uses Worksheets("Logs").Range("B2").Value = 8. The other workbook is active. Which cell changes, and what would remove that workbook dependence?
  1. B2 in the active workbook; name the target workbook too.
  2. B2 in the code's workbook; name the target sheet again.
  3. B2 in both workbooks; add an absolute cell reference.
  4. B2 in the active workbook; remove the Value property.
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

What kind of VBA operation is Range("C2").Value = 75?
  1. Calling a selection method
  2. Declaring a numeric variable
  3. Starting a workbook event
  4. Setting an object property
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A macro selects B1:D1 and then runs Selection.Font.Bold = True. What direct command performs the same formatting?
  1. Range("B1:D1").Value = True
  2. Range("B1:D1").Font.Bold = True
  3. Selection.Range("A1").Font.Bold = True
  4. Range("B1:D1").Font.Bold = False
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A report has headers in row 1 and an ID in column A for every record through row 83. A last-row calculation on A is used to form Range("B2:F" & lastRow). How many data rows does that range contain?
  1. 82 rows
  2. 83 rows
  3. 81 rows
  4. 84 rows
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Which VBA structure repeats the enclosed commands for every cell in a specified range?
  1. With ... End With
  2. If ... End If
  3. For Each ... Next
  4. Sub ... End Sub
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A macro uses If cell.Value > 700 Then to flag numeric entries. The values are 690, 700, and 715. Which value is flagged?
  1. 700 and 715
  2. 690 and 700
  3. 715 only
  4. All three values
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A data sheet has records in rows 2–18 and 20–27, with row 19 entirely blank and IDs in column A on every record. Code uses Range("A1").CurrentRegion and omits the later records. What change fits the full row span?
  1. Find the last row from A and build a range through that row.
  2. Keep CurrentRegion and change the starting cell from A1 to A2.
  3. Use the number of visible rows in the first block as the final row.
  4. Find the last row from A and subtract the blank row from its address.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A report procedure contains If MsgBox("Remove old rows?", vbYesNo) = vbNo Then Exit Sub before its deletion commands. A user chooses No. What runs after that choice?
  1. The deletion runs, then the procedure ends.
  2. The procedure pauses until F5 is pressed.
  3. The remaining commands still run normally.
  4. The procedure ends before deleting rows.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

During F8 stepping, a line is highlighted yellow. Has that line already executed?
  1. Yes; it was the last line executed.
  2. No; it is the next line to execute.
  3. Yes; yellow marks a completed test.
  4. No; yellow marks a comment to skip.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A macro completes without messages, but new records below row 45 are missing from its results. Its code uses a fixed range ending at row 45. What kind of error is this?
  1. A syntax error
  2. A logic error
  3. A compile error
  4. A run-time error
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A macro pauses before a loop. The Immediate window shows 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?
  1. Qualify the intended sheet in the row calculation and the loop range.
  2. Increase lastRow to 91 permanently and keep the active-sheet references.
  3. Move the breakpoint after the loop and keep both range references.
  4. Qualify only the loop range and keep the existing row calculation.
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

What does the usual Disable VBA macros with notification setting do when normal file trust rules apply?
  1. Disables code and offers a file-specific trust notice.
  2. Runs code and shows a notice after it has finished.
  3. Disables code and removes its VBA from the workbook.
  4. Runs signed code and silently deletes unsigned code.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An unexpected attachment claims to be a delivery invoice and says "Enable Content to read." What is the appropriate response?
  1. Enable macros because the message names a delivery.
  2. Enable all VBA globally so the invoice can open normally.
  3. Leave macros disabled and verify the request independently.
  4. Mark the Downloads folder trusted before opening the file.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A recorded formatting macro works with Trust access to the VBA project object model off. Why is enabling that option unnecessary for this task?
  1. It governs the workbook's display language, not cell formatting.
  2. It governs the macro shortcut letter, not cell formatting.
  3. It governs the saved worksheet names, not cell formatting.
  4. It governs automatic access to project code, not cell formatting.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A downloaded workbook shows a red Security Risk bar with no Enable Content button in Windows Excel. What commonly caused that block?
  1. The file uses relative cell recording.
  2. The file carries an internet-origin marker.
  3. The workbook has an unsaved description.
  4. The workbook contains too many worksheets.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A developer changes a procedure after digitally signing its VBA project. What must happen before distributing the edited code with a valid signature?
  1. Keep the old signature unchanged.
  2. Sign the changed project again.
  3. Rename the button's worksheet.
  4. Resave in macro-free format.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A team wants the same verified SharePoint macro workbook in desktop Excel, with fewer repeated Windows internet-block steps. It also wants to avoid trusting unrelated downloads. What arrangement best fits?
  1. Browser-download every copy into a trusted Downloads folder.
  2. Browser-download every copy and turn off notifications globally.
  3. Move all received attachments into a new shared trusted folder.
  4. Use the controlled SharePoint copy with Open in Desktop App.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A team macro refers to Range("SalesData"). Rows are inserted above that named range. Why is this reference useful compared with a literal address string?
  1. The range name can follow its cells as their addresses move.
  2. The range name automatically repairs every VBA sheet name.
  3. The range name makes all worksheets identical on every run.
  4. The range name prevents users from inserting any other rows.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A team tool works on the author's Windows computer. A colleague uses desktop Excel for Mac, and another uses Excel on the web. What should the author verify before sharing it as a VBA tool?
  1. Lock the VBA project and promise it will run on both recipient platforms.
  2. Save as .xlsx and tell both recipients to run the existing macro button.
  3. Test Mac-compatible behavior and tell browser users to use desktop Excel.
  4. Add a Workbook_Open event so the web user can trigger VBA automatically.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A macro stops with error 9 at Worksheets("Archive "), but the visible tab is named "Archive". What edit addresses that mismatch?
  1. Add a trailing space to the procedure's Sub name.
  2. Replace the quoted name with the color of the sheet tab.
  3. Remove the trailing space inside the quoted name.
  4. Move the line into the macro's description comment.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A procedure fails when selecting a range on a sheet that is not active. The only required result is to make that range bold, and no later command needs a changed selection. What edit best removes the cause?
  1. Keep the Select command and rename the Sub procedure.
  2. Set Font.Bold directly on the fully named target range.
  3. Set the active sheet's full column to bold without naming the range.
  4. Keep the Select command and move it after the Selection formatting.
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

What language does Excel's Office Scripts Code Editor use?
  1. VBA
  2. Python
  3. TypeScript
  4. Google Sheets formulas
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An Excel workbook stays in .xlsx format but runs an associated Office Script. Where is that script stored?
  1. Inside the workbook's hidden VBA module.
  2. In a separate OneDrive or SharePoint .osts file.
  3. In the user's local PERSONAL.XLSB workbook.
  4. Inside the workbook's first worksheet formula.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A colleague inside the organization can edit a shared workbook and has Office Scripts available. An associated script works manually, but its fetch call fails when Power Automate runs it. What explains that difference?
  1. The colleague needs read-only workbook access to use fetch.
  2. Office Scripts must be embedded in .xlsm before a flow can use them.
  3. The colleague must enable VBA project access for the script run.
  4. External calls are restricted in the Power Automate script run.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Where does a Google Sheets recorded macro keep its JavaScript function?
  1. In the spreadsheet's bound Apps Script project.
  2. In the desktop Excel Personal Macro Workbook.
  3. In a VBA standard module inside the spreadsheet.
  4. In a separate Office Script file on SharePoint.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A simple onEdit trigger tries to email a registration summary and cannot use the email service. Why?
  1. Every Apps Script function must be a recorded macro first.
  2. Bound projects cannot access the sheet that contains them.
  3. Simple triggers cannot use services requiring authorization.
  4. Time-driven triggers run only while the sheet is being edited.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A Google Sheets owner makes a normal copy of a spreadsheet containing recorded macros. What happens to its bound script project?
  1. It is converted into an Office Script.
  2. It is copied with the spreadsheet.
  3. It stays behind as a local desktop file.
  4. It becomes a set of worksheet formulas.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A consumer account has 90 minutes of daily Apps Script trigger time. It has already used 64 minutes. Five remaining scheduled jobs each take 6 minutes, with no other trigger activity. Can all five complete within that daily allowance?
  1. No; they need 30 minutes, but only 26 remain.
  2. Yes; each job is within the 6-minute execution limit.
  3. No; they need 26 minutes, but only 24 remain.
  4. Yes; the daily allowance resets after each execution.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A maintenance analyst formats a local Excel export in the same way each week and must work offline. What automation tool best fits that environment?
  1. A cloud Office Script
  2. A timed Apps Script
  3. A Sheets onOpen trigger
  4. A desktop VBA macro
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A supported Microsoft 365 team keeps a workbook and team script on SharePoint. It needs updates at 6:30 without anyone opening Excel, and the script uses only workbook operations. What setup meets those needs?
  1. An Office Script called by a scheduled Power Automate flow.
  2. A VBA Workbook_Open procedure saved in the SharePoint workbook.
  3. A manually run Office Script that checks the clock when clicked.
  4. A VBA macro in the owner's PERSONAL.XLSB with a shortcut key.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A group moves a VBA workflow to Google Sheets and needs an authorized daily email from the new version. What work must be planned?
  1. Convert to Sheets and reuse the existing VBA opening event.
  2. Rebuild in Apps Script and use an unauthorized simple onEdit.
  3. Copy VBA into an .osts file and schedule that file in Sheets.
  4. Rebuild in Apps Script and use an authorized time-driven trigger.
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

A task takes 14 minutes by hand and 4 minutes per automated run including checking. Setup takes 300 minutes, and 36 runs are expected before the layout changes. The change adds 80 minutes of maintenance. What is the net time result for those 36 runs?
  1. Automation saves 60 minutes overall.
  2. Automation saves 140 minutes overall.
  3. Automation costs 80 minutes more.
  4. Automation costs 20 minutes more.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A relative macro formats a row by moving right from its first cell. It works when started in column A but shifts the formatting when started in column B. What starting instruction should accompany it?
  1. Select the first cell of the target row before running.
  2. Select the last used cell of the target row before running.
  3. Select any cell because relative mode finds the row automatically.
  4. Select the first cell only after the macro has already finished.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Column A has an ID for every record through row 96; column D has optional notes ending at row 72. A loop must check all 95 data rows in E, below headers in row 1. What design fits?
  1. Find lastRow from D, then loop through E2:E72.
  2. Find lastRow from A, then loop through E2:E95.
  3. Find lastRow from A, then loop through E2:E96.
  4. Find lastRow from D, then loop through E1:E96.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A procedure is renamed from FormatExport to PrepareExport. Its worksheet button still names FormatExport. Why does the button fail?
  1. The renamed procedure must be saved in .xlsx first.
  2. Its assignment still points to the old procedure name.
  3. The procedure must move into the Immediate window.
  4. A new procedure name automatically requires relative recording.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An edited macro colors amounts above 900. The test data contain 899, 900, and 901; only 901 should be colored. The run finishes, but 900 and 901 are colored. What is the most useful debugging step?
  1. Step through the If test and inspect its comparison operator.
  2. Clear all breakpoints and accept the completed run.
  3. Unblock the file because the workbook produced no warning.
  4. Copy the module again to make the threshold update automatically.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A verified Windows download is unblocked in file Properties, but its unsigned macros remain disabled under an organization's signed-only policy. Why does unblocking fail to make them run?
  1. It changes the code language but not the workbook's file format.
  2. It enables code only when the workbook has relative references.
  3. It removes the origin marker but does not override macro policy.
  4. It signs the workbook data but does not rename the VBA module.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What should users consult to learn the expected input layout and the maintainer of a shared macro workbook?
  1. The current Windows Downloads list
  2. The workbook's Instructions sheet
  3. The VBA editor's font-color setting
  4. The workbook's recent cell selection
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A team script is associated with a workbook but remains in a departing employee's OneDrive. What change addresses continuing team access?
  1. Embed its TypeScript in an .xlsm VBA module.
  2. Give every recipient read-only workbook access.
  3. Record each run as a new personal desktop macro.
  4. Move team-owned script storage to SharePoint.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A simple onEdit job takes 44 seconds and sends an email. Its owner proposes running the same work on a daily authorized time-driven trigger. How does that address the two stated problems?
  1. It removes all quotas and lets email run without authorization.
  2. It keeps the 30-second limit but changes the spreadsheet's file type.
  3. It permits authorized email and uses the longer installable-trigger run limit.
  4. It makes simple triggers authorized and keeps their original timing.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An existing Power Query process already performs a repeated import and cleanup correctly. What should the analyst try before writing custom VBA for the same work?
  1. Refresh the existing query.
  2. Record every import again.
  3. Convert the query into a VBA event.
  4. Move the data to another platform.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

79 Key Terms, each with its definition

A

Absolute recording
Absolute recording stores the fixed addresses of selected cells, making those recorded selections return to the same positions.
Absolute recording stores the A1:E1 header selection so later runs return to those same cells.
Action Recorder
The Action Recorder captures supported Excel actions as Office Script steps and shows them in a pane while recording.
The Action Recorder lists the header selection and bold setting before the user stops the recording.
Active cell
The active cell is the cell that receives an entry, and VBA can refer to it through ActiveCell during a macro run.
An ActiveCell entry writes to D8 when D8 is the active cell at the moment that line executes.
Authorization
Authorization grants a script permission to access specified protected data or services on behalf of the approving user.
Before granting authorization, the user reads the summary script's requested sheet and email permissions.
Automation maintenance
Automation maintenance keeps code, permissions, instructions, and tests working as layouts, software, users, or task rules change.
Automation maintenance after a header move includes updating the macro and checking known test results.
Automation platform
An automation platform supplies the application environment, code storage, and running options in which an automated process works.
The team selects an automation platform for Sheets because both its users and registration data work there.
AutoSave
AutoSave continuously saves changes to supported cloud-stored Office files, including workbook changes made by a running macro.
The tester uses a separate copy because AutoSave could preserve changes before the workbook is closed.

B

Bound script project
A bound script project belongs to a specific Google file, such as a spreadsheet, and is copied when that file is copied.
A duplicate registration spreadsheet includes the bound script project containing its recorded macros.
Break mode
Break mode is the paused execution state in VBA, where you can inspect values or step through code before continuing or resetting.
The procedure is still in break mode after the analyst examines the highlighted line.
Break-even point
The break-even point is the number of runs at which accumulated time savings repay the time spent building and testing automation.
A tool with a 100-minute setup and a 5-minute saving per run reaches its break-even point at 20 runs.
Breakpoint
A breakpoint marks a code line where execution pauses before that line runs, allowing inspection of the current state.
The analyst sets a breakpoint before the loop to inspect the calculated last row.

C

Change log
A change log is a short record of versions and edits that helps users and maintainers understand how a macro workbook has changed.
The change log records that version 1.3 now expects an extra status column in the input.
Code-signing certificate
A code-signing certificate is a digital credential used by a developer to sign a VBA project and identify its publisher.
The developer selects a code-signing certificate through Tools > Digital Signature in the editor.
Comment
A comment is explanatory text ignored during code execution; in VBA an apostrophe begins a comment on that line.
The comment "Column A contains order IDs" explains why the macro uses that column to find its last row.
Compile error
A compile error prevents VBA from preparing code to run, for example when a procedure name is unknown or a variable is undeclared.
An undeclared variable produces a compile error under Option Explicit when the analyst starts the macro.
Constant
A constant is a named value used by code, including Excel's built-in xl names for settings and navigation directions.
The macro uses the constant xlUp as the direction when moving from the bottom of the key column.
CurrentRegion
CurrentRegion is the range around a cell bounded by blank rows and blank columns, often used to refer to a data block.
An entirely blank separator row makes CurrentRegion stop before the next block of records.

D

Developer tab
The Developer tab is an Excel ribbon tab containing macro recording, code editing, and macro security controls.
The analyst enables the Developer tab before opening Record Macro for the first time.
Digital signature
A digital signature identifies the signer of a VBA project and supports verifying that its code has not changed since signing.
After editing the procedure, the developer applies a new digital signature before sharing it again.

F

For Each loop
A For Each loop repeats commands for the members of a collection, such as visiting every cell in a specified range.
The For Each loop checks D2, then D3, and continues through the last amount cell in the report.

G

Google Apps Script
Google Apps Script is Google's JavaScript automation platform for Workspace apps, running code on Google's servers.
A Sheets registration list uses Google Apps Script to prepare and email its daily summary.

I

If statement
An If statement tests a condition and runs its associated commands when that condition is true, adding a decision to code.
The If statement colors an amount only when cell.Value > 1000 evaluates to True.
Immediate window
The Immediate window is a VBA editor panel for evaluating expressions, running single commands, and displaying Debug.Print output.
Typing ? ActiveSheet.Name in the Immediate window reveals the sheet currently used by the test.
Instructions sheet
An Instructions sheet explains a workbook tool's purpose, start controls, required input layout, and maintenance details to its users.
A colleague reads the Instructions sheet to find the button that starts the tool and the required export columns.

J

JavaScript
JavaScript is the programming language used by Apps Script functions, including code created by the Google Sheets macro recorder.
The recorded JavaScript function calls setFontWeight("bold") to format the selected header.

L

Last-row calculation
A last-row calculation finds the end of data in a chosen column so code can build a range matching the current records.
A last-row calculation scans upward in an ID column before the code builds a range of amounts that ends on the same row.
Logic error
A logic error makes a macro produce the wrong result even though its commands are valid and execution may finish normally.
A logic error leaves new records out when a procedure written for a fixed range still reports success.
Long
A Long is a VBA whole-number data type commonly used to store worksheet row numbers, including the last data row.
Declaring Dim lastRow As Long prepares a suitable variable for an Excel row number.

M

Macro
A macro is a stored sequence of commands that a spreadsheet program can replay to carry out a repeatable task.
A macro applies the same header formatting whenever a new export arrives from the reporting system.
Macro assignment
A macro assignment links a button, shape, or other control to a named procedure so that using the control starts that code.
After renaming the procedure, the analyst updates the button's macro assignment to the new name.
Macro description
A macro description is text explaining a macro in the Macro dialog and copied by the recorder into comments above its commands.
The macro description "Fit the report columns" helps a colleague choose the right procedure from the list.
Macro dialog
The Macro dialog lists available macros and provides commands to run, edit, delete, step into, or change options for them.
The user presses Alt+F8 and filters the Macro dialog to show only macros in the current workbook.
Macro recorder
The macro recorder turns supported spreadsheet actions into code, including extra actions and corrections made while recording.
The macro recorder captures a mistaken column selection along with the later correct selection.
Macro security setting
A macro security setting controls whether VBA is disabled, prompts for a trust decision, or can run under specified trust rules.
The signed-only macro security setting distinguishes trusted publishers' code from unsigned projects.
Macro shortcut
A macro shortcut is a key combination assigned to start a procedure, taking over any matching Excel shortcut while available.
The analyst assigns Ctrl+Shift+J as a macro shortcut to start cleanup without opening the macro list.
Macro-enabled template
A macro-enabled template is an .xltm file used to start new workbooks with a prepared layout and reusable VBA code.
The department starts each new report from a macro-enabled template containing its formatting procedure.
Macro-enabled workbook
A macro-enabled workbook uses a file format capable of retaining VBA, with .xlsm the usual format for a new macro workbook.
The shared report is a macro-enabled workbook so its formatting procedure stays inside the file.
Macro-free workbook
A macro-free workbook uses a format such as .xlsx that stores workbook data and features without retaining a VBA project.
The analyst saves a macro-free workbook in .xlsx format after removing the need for its old VBA tool.
main function
The main function is the starting function of an Office Script and receives the workbook object used by its commands.
The main function begins the script and gets the active worksheet from the supplied workbook.
Mark of the Web
The Mark of the Web is a Windows internet-origin marker that makes Office apply additional checks and default macro blocking.
A browser-downloaded macro workbook opens with a red block because it carries the Mark of the Web.
Method
A method is an action an object can perform, sometimes using arguments to specify how that action should work.
The AutoFit method adjusts report column widths to fit their displayed contents.
Module export
A module export saves a standard VBA module as a .bas file so its procedures can be imported into another workbook project.
The maintainer uses a module export to transfer the cleanup procedures into the new reporting project.
MsgBox
MsgBox is a VBA command that displays a message or a question and can return the button a user selects.
The macro uses MsgBox with Yes/No buttons to ask for confirmation before deleting old report rows.

N

Named range
A named range gives cells a meaningful name that code can use and that can follow the data through row or column insertions.
The named range SalesData follows its cells after a row is inserted above the data block.
No-code alternative
A no-code alternative uses a built-in feature such as a formula, table, or refreshable query to perform work without custom script code.
The analyst chooses conditional formatting as a no-code alternative for coloring overdue entries.

O

Object
An object is a workbook, worksheet, range, or other application component that code can address and work with.
The macro reaches the Report worksheet object before setting properties on its header range.
Office Scripts
Office Scripts is Excel's TypeScript automation system, with an Action Recorder and editable scripts stored in cloud files.
The team uses Office Scripts to format the header of its shared browser-based Excel report.
Offset
Offset identifies a range displaced by specified row and column counts from another range; positive values move down and right.
From D6, ActiveCell.Offset(-2, 1) refers to E4 because it moves up two rows and right one column.
Option Explicit
Option Explicit is a module-level VBA statement requiring variable declarations, helping catch undeclared or mistyped names.
With Option Explicit, the typo lastRwo is flagged instead of silently creating a different variable.

P

Personal Macro Workbook
The Personal Macro Workbook is hidden PERSONAL.XLSB, loaded when Excel starts to supply personal macros across workbooks.
An analyst keeps a general formatting tool in the Personal Macro Workbook for use with many exports.
Power Automate
Power Automate is a Microsoft workflow service that can call Office Scripts on a schedule or in response to workflow events.
A scheduled Power Automate flow calls the report script while no user has the workbook open.
Project Explorer
Project Explorer is the editor panel that groups each open workbook's VBA code into sheet, workbook, and standard modules.
The analyst expands the report's project in Project Explorer before opening its Module1.
Property
A property is a value or setting belonging to an object, such as a cell's contents or the bold setting of its font.
Setting Range("B1").Font.Bold = True changes a property of the font used in B1.

Q

Quota
A quota is a service limit on use, such as total trigger running time per user per day, that can stop script execution when exceeded.
Several scheduled jobs share the user's daily trigger-time quota, so each run must be kept small enough.

R

R1C1 notation
R1C1 notation describes formula references using row and column numbers, with square brackets indicating relative offsets.
In R1C1 notation, R[-1]C names the cell one row above the formula in the same column.
Relative recording
Relative recording stores cell movements from the active cell, allowing the actions to follow a different starting position.
Relative recording makes a one-row-down movement end at E10 when the macro starts from E9.
RGB
RGB specifies a color using red, green, and blue component values, making a numeric VBA color easier to understand and edit.
The code uses RGB(0, 176, 240) to apply the same light blue as hexadecimal color #00B0F0.
Run-time error
A run-time error interrupts an executing macro when a command cannot be completed, producing a numbered error message.
A worksheet reference produces run-time error 9 because its name no longer matches a tab.

S

Selection
Selection is the object currently selected in Excel; recorded code often applies formatting to that selection after selecting cells.
A misplaced Select command changes the cells that a later Selection.Font.Bold statement formats.
Simple trigger
A simple trigger is a reserved Apps Script function, such as onEdit, that runs for a supported event without authorization.
A simple trigger named onOpen adds a menu but cannot use an email service requiring authorization.
Spreadsheet automation
Spreadsheet automation uses stored rules or commands to repeat spreadsheet work with less manual action.
Spreadsheet automation repeats the weekly cleanup because every export has the same columns and header row.
Standard module
A standard module is a code container in a VBA project where recorded macros and other general procedures are stored.
Two formatting procedures share a standard module in the workbook's Modules folder.
Sub procedure
A Sub procedure is a named VBA block beginning with Sub and ending with End Sub that carries out a sequence of commands.
The Sub procedure named FitReport groups the commands that set the report's column widths.
Syntax error
A syntax error occurs when code does not follow the language's required form, such as a string with a missing closing quote.
Deleting the final quote from a worksheet name creates a syntax error that turns the line red.

T

Time-driven trigger
A time-driven trigger is an installable Apps Script trigger that starts a function on a cloud schedule, even with the file closed.
A time-driven trigger starts the daily summary while nobody has the spreadsheet open.
Trust Center
The Trust Center is the Office settings area that manages security and trust controls, including Excel's macro settings.
The analyst opens Trust Center to review the macro notification setting for desktop Excel.
Trusted document
A trusted document is a file whose active content the user has chosen to trust, allowing Office to remember that file-specific decision.
A familiar workbook no longer shows a macro warning when it opens after it has become a trusted document.
Trusted location
A trusted location is a configured folder whose Office files can bypass security checks and open with macros enabled.
The team limits write access to its trusted location so unexpected macro files cannot be added there.
Trusted publisher
A trusted publisher is a signer whose certificate has been trusted, allowing its signed macros under compatible security settings.
A project signed by the organization's trusted publisher can run under its signed-macros policy.
TypeScript
TypeScript is a language based on JavaScript that adds data types and is used to write Office Scripts for Excel.
The TypeScript code describes its workbook parameter with the type ExcelScript.Workbook.

U

Unattended run
An unattended run starts and performs work without a person launching it at that moment, typically through a cloud schedule or event.
An unattended run updates the workbook overnight through a cloud workflow without an open desktop session.

V

Variable
A variable is a named place for a value that code uses while running, such as the changing row number stored in lastRow.
A lastRow variable receives 74 one week and 91 the next when the number of records in a weekly export changes.
VBA
VBA, or Visual Basic for Applications, is the programming language built into desktop Office for automating its applications.
The Excel recorder writes VBA when an analyst selects a header and changes its font and fill.
VBA project lock
A VBA project lock is password protection that deters casual code viewing or editing but is too weak to secure stored secrets.
A VBA project lock deters casual edits to the report code, while passwords stay out of its procedures.
VBA project object model access
VBA project object model access permits software to work with VBA project code automatically and is disabled by default.
VBA project object model access stays off while an ordinary recorded macro formats the report cells.
Version History
Version History stores earlier versions of a cloud file that can be restored when later changes need to be reversed.
The maintainer uses Version History after an AutoSaved macro test changes the wrong report data.
Visual Basic Editor
The Visual Basic Editor is the Office code-editing environment used to locate, read, change, and debug VBA procedures.
Alt+F11 opens the Visual Basic Editor so the analyst can inspect the recorded formatting code.

W

With block
A With block groups commands for one VBA object, using leading dots to refer to that object without repeating its full name.
Inside a With block naming A1:C1, .Font.Bold refers to the font of that same header range.
Workbook_Open event
The Workbook_Open event starts a procedure in ThisWorkbook when the workbook opens in desktop Excel with macros enabled.
The tool uses the Workbook_Open event to display its Instructions sheet before the user starts work.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started