Ravindra BagaleCourses & study guides मराठी Track your progress

12. Macros and VBA

Excel

12.1 Developer Tab, Macro Security and .xlsm

Sana at the fictional NovaCraft Tools shop closes a tiny packing report every afternoon. She wants its header to have the same bold style each day. When she creates a macro, she needs a place to open the recording tools, a file that can keep the code and permission to run what she wrote. Treat these as three separate checks and you can explain most first-day failures.

Three checks before you record

Find the command, save the code, follow the policy

Think about a small shop that lists goods on a marketplace such as Amazon. Staff might receive a new workbook for each batch. Our packing worksheet, names and figures are fictional and do not describe a marketplace's own operations. Sana's Practice sheet tracks Tape and Labels. She can check the prices, apply the bold style in two cells and inspect the exact range before saving. Making the example this small gives her the freedom to repeat it without touching an order or changing a shop setting.

Find the Developer tab, store the procedure in an XLSM practice copy, and run only your own reviewed macro under existing policy.
Make the tools visible first, then decide where the code belongs and whether your environment allows the practice run.
  • Visibility: The Developer tab is a set of controls at the top of desktop Excel. It gives you access to the recorder, the list of macros and the Visual Basic Editor. Showing that set of controls is a ribbon preference for your app. Your supervisor opening the same file may have a different ribbon preference.
  • Storage: An Excel macro-enabled workbook, normally carrying the .xlsm extension, is a workbook type that can keep a VBA project. A project contains the workbook's code and related VBA objects. When you record in This Workbook, that is where you expect the procedure to be saved.
  • Execution: A stored procedure changes things when it runs. Your desktop application and applicable settings determine whether a macro can run. This decision considers policy and trust in the file and its source. A visible Developer tab and a correct file extension get you only as far as finding the command and keeping it.
  • Verification: The job is complete when you can name the workbook and read back the right values and formatting. Here the two header cells should be bold, the amounts should stay seventy-five and one hundred twenty, and the combined total should remain one hundred ninety-five.

Give the first macro a small job

Choose one action that you can reverse manually or discard by closing an independent copy. Applying Bold to two text labels is a useful first action. It can be seen immediately, does not require writing a formula in the recorder and does not depend on outside data. If the row contains labels and the next row contains values, read the formula bar and the values after the action too. A macro can change a cell on the original sheet even when a different one is in view, so place a note on a second tab and inspect it directly.

Use a meaningful procedure name such as StylePackingHeader. A reader should predict its output from the name. The name uses letters and no spaces. Keep the practice purpose and scope together in a short description, such as “Makes Practice A1:B1 bold.” Later the Macros dialog can show multiple commands across open workbooks. This name and description help you identify the correct one before pressing Run.

Remember: A missing toolbar, a workbook saved without its code and a blocked procedure are different problems. Solve the one you can observe before changing anything else.

Find the Developer tools on desktop

Windows desktop Excel

  1. Open your own blank workbook. Find File in the ribbon, open Options and choose Customize Ribbon. The screen is for your app's ribbon arrangement. You may see a left column representing available commands and a right column for the tabs currently shown.
  2. Under Main Tabs in the ribbon structure, select Developer and confirm with OK. Expect a Developer label on the ribbon when you return to the workbook window. Look for Visual Basic, Macros and Record Macro in the code controls. Button names can collapse into icons when the window is narrow.
  3. Find Record Macro and Cancel if you opened its setup form only to look around. The recorder is active after you confirm its details until you deliberately stop it. Avoid clicking through other tabs while recording a single formatting task. For this lesson, first save the correctly named training file.
  4. You can find Macro Security in the Windows Developer tools, or under Trust Center settings in File Options. The exercise does not require changing those settings. If your organization controls the choices, follow its process and use the paper trace when execution is restricted.

Mac desktop Excel

Start from the Excel menu in the Mac menu bar, then go to Preferences or Settings, followed by Ribbon & Toolbar. In Customize the Ribbon, find the Main Tabs list and select Developer. Save if the dialog offers a Save control, then close Settings and inspect the Excel window. The Developer controls let you open Visual Basic, see macros or start a recording. The ribbon location, menu terms and shortcuts can vary with app version. Use the actual words in your copy of Excel and follow the current Microsoft for Mac instructions.

The course will later discuss tools that are available for some Windows desktop configurations but do not behave the same on Mac, such as ActiveX controls. For this exercise, no button or add-in needs to be installed. A standard module holding one simple formatting procedure and a direct run through the dialog are sufficient. The numerical outputs have the same meaning on each supported desktop.

Excel for the web

The browser can show and edit workbook cells while preserving existing VBA in a supported workbook. It cannot create, run or edit that VBA. If you open a workbook in a browser and can see its packing list, you have verified access to the spreadsheet data. Running its formatting macro still requires an approved desktop session. A browser tab named Automate, when available, belongs to Office Scripts and is studied in later lessons.

  • See the right product: A file preview from an email, a Teams tab, Excel in a browser and Excel desktop can show similar cell grids. Determine which app you are in before following platform-specific menu paths.
  • Confirm the ribbon preference: Close or collapse a ribbon may hide the controls even after enabling the tab. Return to the workbook and check the tab row. Look for the actual tab label before concluding that the file lacks a macro.
  • Confirm the workbook type separately: You can show Developer in an ordinary XLSX workbook. The ribbon is still useful for inspecting tools, while the file type determines whether any code you add is saved.
  • Keep your practice isolated: Close unrelated workbooks if practical or give your file a distinctive title and tab. This makes it straightforward to see which workbook the Macros dialog is showing. There is no requirement to change how coworkers use their copies.

Pick a file type for its contents

Keep one master for the code and another copy for data

Windows and Mac both offer a file type list in Excel's Save As or Save a Copy dialog. Choose Excel Macro-Enabled Workbook in the list for the main practice file. Use a name that identifies its purpose, such as PackingPracticeCode.xlsm. An Excel Workbook, which carries an .xlsx extension, preserves ordinary cells, formulas and formatting, but cannot save a VBA project. Use that type for a separately named file meant for somebody who needs the packing report without its automation.

Both XLSM and XLSX copies keep workbook formulas. Only the XLSM copy of the example keeps its VBA project.
Choose the format in Excel, reopen both copies by name and inspect the formula and procedure separately.
File formats you may meet while learning VBA
TypeCan store VBA?Typical use
XLSXNoWorkbook data and formulas
XLSMYesWorkbook with VBA procedure
XLSBYesWorkbook in binary file format
XLAMYesExcel add-in with commands or code
XLTMYesMacro-enabled template for starting a workbook
  • XLSM: The file can hold macros even if you have not added any yet. When you first save the blank practice file in this format, there may be nothing in its Macros dialog. After creating a procedure, save again and check the list after reopening.
  • XLSX: When you deliberately make a data-only copy of this lab, opening it should show the same two amounts, total and header formatting without that file's VBA project. Other open workbooks can still advertise their macros. Choose This Workbook in the dialog or inspect the actual project when comparing files.
  • XLSB: This is another workbook representation that can hold VBA. It is not an automatic performance or safety upgrade. If someone offers a binary workbook, treat code review, source and applicable policies with the same care.
  • XLAM and XLTM: An add-in extends Excel with a packaged capability. A template gives a starting layout or code to other workbooks. Ordinary reusable practice can live in a separate XLSM copy. You do not have to install an add-in or publish a template to complete this lesson.

Read the Save prompt before answering

Excel may tell you that the VBA project cannot be saved in a macro-free workbook. This may happen when you save a new macro, when you change the file type, or when you export a separate copy. Read the prompt in your own version. If you mean to keep the project, use the option that stops the macro-free save and choose XLSM. If you mean to make a separate data-only copy after preserving the original, choose the macro-free format and confirm the option that discards the project from that copy. A filename that ends in XLSM after someone changes a label in Finder is not a format conversion.

Saving to the right format can preserve complicated things like formulas, style and procedure code. A correct file can still look wrong after reopening if you changed its pathname or if automatic saving applied to a different copy. Write down the specific filename and folder. If both types are visible as PackingPractice because your file manager hides extensions, open Windows or Mac Excel's information for the workbook or check the file properties for its full name. Design file names with distinct meanings so you can spot the data copy even if a system abbreviates the extension.

Read the trust decision before running

Understand the security settings without changing them

A worksheet formula is part of the calculation model. A VBA procedure can take sequences of actions such as editing cells or files through its host's permissions. Microsoft and your administrator may restrict which code can run. A useful practice solves a tiny known task under existing rules. There is no need to configure broad trust or change a protected setting to reproduce the paper exercises here.

  • Disable without notification: A restriction can disable macros without presenting a choice to run them. A workbook may still show its data. If the controls say your policy is managed, ask the organization how to take the class under its rules.
  • Disable with notification: Excel can warn and treat trust case by case where that is permitted. This is discussed in Microsoft's desktop Excel settings. An internet macro block or organizational rule can still apply. A button you see in one version or file may be absent on another.
  • Signed macro restriction: A digital signature lets a verifier check the signing identity and whether the signed project was changed. Whether a signer is trusted and whether the code is allowed depend on policy and the particular file. If the workbook contains a signature, your organization can still require review of its code and provenance.
  • Allow all setting: Some settings screens offer a choice that broadly allows macros. This expands which code could run. It is inappropriate for this exercise. Leave the setting in place and use the approved training option or the offline trace.
  • Trusted managed locations: Organizations may manage specific locations or publishers for their own approved tools. Broadly trusting a folder makes the set of people who can write there important. No location or publisher needs to be added to work through a practice file you create under the current rules.

When a workbook comes from outside

A file from the internet or an email attachment can carry source information. Windows Office can use a Mark of the Web to recognize that a file originates outside the expected local trust boundary. For supported Microsoft 365 Apps cases, it can block its macros with a Security Risk message rather than offering the same prompt as an ordinary local file. File storage, delivery path and the organization's settings affect the experience. A Mac may present different controls. Follow the meaning of the warning and keep existing protections in place.

Suppose Sana receives a message from an unfamiliar account promising a finished packing tool. She needs only a list of sample parts. She can work in a fresh workbook using the made-up part and price values below. If the tool is a required shop dependency, she asks the responsible team to identify the publisher and approved version. This is a practical handoff question: “What is the approved client, workbook name and version, and which actions should the macro perform?” Verify that answer through your established channel before running anything more powerful than routine formulas.

Safe learning branch: Read the code shown here and predict the three amounts without opening someone else's macro-enabled file. If your own sandbox can run its reviewed macro under current settings, verify the same values inside the copy.

Lab one. Keep a one-action macro after reopening

Set up the exact practice cells

Type the sample on the Practice worksheet starting in A1
PartUnitsUnit costAmount
Tape32575
Labels430120

Enter the part labels, units and cost from the table. Use the following formulas instead of typing the displayed amounts. The first calculation multiplies Tape's three units by twenty-five rupees. The second multiplies four by thirty. The sum joins the two amounts, so a precise result for the last cell is one hundred ninety-five. In another sheet called Notes, keep a text marker such as “Keep these notes.” Start with the default unbold style on the Practice header. Use the values below to check that the first macro only adjusts formatting.

D2: =B2*C2
D3: =B3*C3
D4: =SUM(D2:D3)

Save, create, inspect and run

  1. Save the project container. In your own training location choose the macro-enabled workbook type and save a copy named PackingPracticeCode.xlsm. Check file type before recording. You can keep a plain copy with the formulas alongside it for recovery. Make sure the first workbook you keep has its own clearly named path.
  2. Record an exact formatting action. In your saved code copy select Practice. Turn Use Relative References off if it is on. Start recording StylePackingHeader and choose This Workbook for storage. Once recording starts, deliberately select A1:B1, apply Bold and stop. No shortcut needs to be assigned for this test. The expected result is bold Part and Units, ordinary Unit cost and Amount, and no change to the data or other sheet.
  3. Inspect what was recorded. Open the Developer Visual Basic editor if available and view the project under PackingPracticeCode. Find the module containing StylePackingHeader. You may see a range selection and formatting of that selection. Code shown by different versions can vary. Match the procedure name, range and only intended effect before replay. If you recorded a selection or worksheet adjustment by accident, start again in your own sandbox.
  4. Save, close and reopen that specific file. Run the macro from the Developer Macros dialog only in your own reviewed copy under the existing settings. Start from the Practice worksheet, since a recorder-created command can refer to the active sheet. Clear the intended bold formatting first to create a visible test. Expect two bold labels and 75, 120, 195 in D2:D4 afterwards.
  5. Check the data after the run. The formula bar for D4 should still show a sum. Inspect Notes independently. Try another deliberately prepared unbold run and make a checklist of what changed. If no action happens, check whether you are in desktop Excel, the macro exists in This Workbook, and policy permits execution.

If you cannot use the recorder, study the manual equivalent below. Compare it with the observed click sequence: select the intended workbook, resolve the Practice worksheet and set Bold on exactly two cells. This code can remove ambiguity once you learn the VBA editor. Choose either this module or the recording as your exercise; remove an old training version first if you intend to recreate an identical procedure name in the same project.

Option Explicit

Public Sub StylePackingHeader()
    ThisWorkbook.Worksheets("Practice").Range("A1:B1").Font.Bold = True
End Sub

Read this statement left to right. It starts in the code's own workbook and goes to a tab called Practice, then selects the reference A1:B1 as its destination without requiring that your displayed selection changes. The font setting is set to True, so a second run sets the same state instead of toggling it off. No other procedure is required. If the workbook or sheet has a different name or protected cell formatting, inspect the course example and the file first instead of enabling broader access.

Trace two independently saved files

  1. Save the code file

    PackingPracticeCode.xlsm starts with both product rows. Record or write StylePackingHeader in this project, then save it again.

  2. Reopen the code file

    Verify the named workbook's procedure and values. Save the intentionally bold state once it passes.

  3. Make the data copy

    Save PackingPracticeData.xlsx in the ordinary workbook format. Its formulas and values stay. Its own VBA project is omitted.

  4. Check both copies

    Open the two files one at a time. Each shows 195 and intact formulas. Only the code file has its own StylePackingHeader procedure.

Lab two. Compare storage, data and procedure evidence

Make a separate macro-free workbook on purpose

  1. After Lab one, confirm you already saved the code file and that the macro is present after reopening. If you cannot run macros, you can still use the formula sheet for the data-only comparison and treat the VBA evidence as an exercise in reasoning.
  2. With the code copy open, use Save As or Save a Copy, choose the ordinary Excel Workbook type and enter PackingPracticeData.xlsx as a new name. When Excel warns that the macro-free type cannot preserve the project, confirm the data-only copy after checking the destination and ensuring the original was saved. Read the wording on your version's dialog.
  3. Close both practice files and reopen the data copy by its exact name. Compare D2:D4 with the expected 75, 120 and 195. Select D4 and verify the calculation remains in the formula bar. The two bold labels, if saved with that formatting, can remain bold independently of whether the VBA is present.
  4. Filter the Macros dialog to This Workbook, or inspect the individual workbook project. StylePackingHeader should be absent from this file. If you see a command with that name, check the workbook picker, personal macro workbook and other open files. A correct check identifies which file defines a command.
  5. Reopen the XLSM copy on its own and check for the procedure. If allowed, format the practice header from the dialog again and keep your separate Notes marker as a second boundary check. Leave the executable training file in your own approved location when you finish. You can close both copies after reading the results.

Compare a change in stored data with a change in behavior

In the data-only copy change Labels' quantity from four to five. Predict that its row amount moves from one hundred twenty to one hundred fifty and the grand total from one hundred ninety-five to two hundred twenty-five. Tape stays at seventy-five. This shows that a macro-free workbook can still recalculate its formulas. You can reset the quantity to four after the check. Now close that copy and reopen the code file. It still shows quantity four and total one hundred ninety-five, because the files have separate contents after the copy.

Set the two practice header cells in the data-only copy back to ordinary formatting. Changing a style manually in the copy does not affect the procedure saved in the code workbook or its current formatting. Compare direct cell entries, formulas, current appearance and separately stored VBA. These parts can support one workflow, but they provide different evidence when you troubleshoot.

  • No Developer tab: Check the app and ribbon preferences. If you are viewing the file in a browser, use the native desktop app when your environment allows it. If you cannot, complete the formula/calculation proof and inspect the sample procedure as text.
  • Saved but absent: Find the file explicitly, inspect its type and look in the right project. If the type lost the VBA, find the preserved original. Saving the same damaged copy under a macro-capable type creates space for code without recovering the original code.
  • Present but blocked: A stored procedure can exist even when execution is refused. Stop and read the message. Look up the organization's approved workflow. Avoid treating a red blocked message as a workbook format error or treating a new extension as a permission change.
  • Runs but targets the wrong sheet: Read the recording before starting again. Look for Range or Selection statements and whether the worksheet is explicit. Work with a disposable copy to fix the targeting. If an unexpected change affects your practice file, close that copy without saving or use the clean backup.

Explain the proof: Two files both show 195 and contain the same visible bold labels. Give one additional observation that distinguishes the copy with VBA from the one without it. Use the workbook-specific procedure list or its project, and identify which file is open.

Use the symptoms to choose the next check

Practice a handoff in four short cases

Describe observable evidence, then say what conclusion it supports. Ask a partner to choose one of these cases without telling you what caused it. Try to establish which file was opened and what actions it performed. Even a technical support request becomes easier when you can separate the app, the stored file and the procedure that has permission to run.

  1. Ravi sees Last edit and Share, but no Developer tab. He is looking at a browser session. Ask him to verify the two input rows and sum there. If he has an approved desktop client, switch to his own practice workbook and show Developer in that app. If only the browser is available, record that the spreadsheet data is accessible and the VBA run has not been tested. A native desktop screenshot from another person proves only that their choices differ from Ravi's environment.
  2. Sana sees the command today and loses it after restarting Excel. Ask which file is open and whether StylePackingHeader was stored in This Workbook. Then ask whether it was saved and reopened as XLSM. When she shows a copy named PackingPracticeData.xlsx, locate the original code copy first. If the original was never saved with the project, reconstruct the two-cell procedure inside a new practice file after rereading the expected scope. Adding a tab to the ribbon cannot restore a code project.
  3. Mira sees a red message on a workbook obtained over email. Ask the team that owns the workflow for its approved version before using it. Meanwhile, verify independent arithmetic and a fresh workbook using the sample here. If it is an essential tool and there is an administrator approval path, follow that path. A coworker saying their workstations use different settings does not tell Mira which code is stored in the attachment.
  4. A supervisor says the worksheet stayed at 195, so the macro did nothing. Tell them what this version is designed to change: bold in A1:B1. Demonstrate it starting from an unbold state and inspect the data to verify it remained the same. For an unrelated comparison, change B3 in the separate data copy and show 225. The development exercise tests whether appearance changes without affecting calculations, while the data check tests the formula dependency. Use both effects to explain the result.

Build a simple record of what you tested

  • Before: Write the workbook's name, app, the sheet in view, the exact contents of A1:B1 and expected amounts. If the tab or file prevents a run, record that before touching the workbook. Keep your own saved fixture so the next attempt starts with the same input.
  • During: Record which procedure was selected and where its code was found. A list headed All Open Workbooks includes more than your active workbook. See whether a workbook name prefixes the entry or choose This Workbook. If the procedure is available only after allowing something the exercise did not require, stop and ask which policy applies.
  • After: Look at cell formatting and formulas as separate checks. To prove A1:B1 alone changed, inspect A1, B1, C1 and D1 directly and compare the Notes tab. For “after reopen,” show the exact stored copy name. Ask another learner to reproduce the same observation on a fresh copy using your notes.

One-line result for your notebook: The code copy kept the procedure on reopening and made two labels bold. The data-only copy kept the formulas and their values, so replacing the Labels quantity changed the total to 225 there while the original retained 195.

Quick checks

Pick the next action from the evidence

File A has a VBA project and File B has the same formulas without code. Which types fit?

Save File A as XLSM, which can preserve the project and formulas. Save File B separately as XLSX, which can preserve the formulas and formatting without a VBA project. Reopen by full pathname and compare only the named project's procedure list. Code elsewhere in the same Excel session does not belong to File B.

Do you need to change macro policy when enabling the Developer tab?

No change to policy is needed to show the ribbon. In Windows desktop Excel, show Developer under the ribbon's Main Tabs settings. In Mac desktop Excel, look under Ribbon and Toolbar preferences. Developer exposes commands. Whether an executable workbook can run them is determined separately.

How wide should the write scope be for StylePackingHeader?

The intended effect is Bold in Practice A1 and B1. Cells C1 and D1, the quantities and prices, the three formulas and the separate Notes tab remain unchanged. This small scope lets you validate a repeated action with facts that you can see and calculate.

Why can you still see bold labels in a file without its macro?

Excel saved a cell formatting effect in the workbook. The current style and the procedure that caused it are separate features. To test file storage, clear the style in an independent practice copy and check the workbook-specific macro list as well as the visible formatting.

Which amount changes when Labels rises from four to five units?

Labels becomes five times thirty, or one hundred fifty. Tape remains seventy-five, so the sum becomes two hundred twenty-five. The worksheet formula handles the change in either supported file format. The macro in this lesson only changes heading style.

An email attachment is blocked and says it has a signed macro. What do you do?

Leave the policy in place. Identify the workbook and expected publisher through your organization, or use a freshly created practice file for this task. A signature is useful evidence about provenance and changes to a signed project, while your organization decides which signed code or locations qualify for use.

Interview and discussion questions

Explain each symptom to a new colleague

What happens if a workbook with macros is saved as XLSX?

The new XLSX file cannot hold that VBA project. Spreadsheet formulas and formatting generally remain, as in the exercise where D4 still adds the two line amounts. The original XLSM can retain its macro if preserved and saved before conversion. Confirm by opening both files separately.

How do you safely test a macro that you just recorded?

Use a disposable copy you own. Inspect exactly where it selects cells and what it changes. Run from a known state, then check the intended result and a nearby cell or note that must remain. Leave workplace protection in place. Undo may be unavailable after the macro changes cells.

Why is a yellow warning different from an internet macro block?

Desktop Excel may present a case-specific notification under one policy. Windows Office and managed environments can separately block macros based on file source or broader policies. Read the actual reason and ask the responsible staff for an approved training process if needed. Keep the tools and file type checks separate.

Does a macro-enabled extension tell you whether the workbook has any VBA?

The extension describes the format's capability. An empty workbook can be saved as XLSM before code is added, so its Macros dialog may still be empty. To verify the stored project, inspect that file in the editor or look for the named procedure in that workbook's scope.

What is your starting test when a macro is visible but the result looks wrong?

Check the expected output with a manual example and make sure you are looking at the destination. Check whether the procedure used the active sheet or named Practice. Reproduce the experiment on a safe copy and compare one intended effect with one unrelated value that should have survived.

Six recall cards

  • Tool visibility

    Show Developer in desktop ribbon settings. The change affects the app's controls and does not grant permission to run a macro.

  • Saved VBA

    XLSM retains an existing VBA project. Choose the actual file type in Save As. Keep a separately named copy when you want data without the code.

  • Browser and desktop

    Excel for the web can open a workbook with VBA. Creating, running and editing the macro belong to desktop Excel.

  • Policy evidence

    A file can contain a macro and be blocked. Read the policy message and use a local trace or approved alternate exercise.

  • Known cells

    StylePackingHeader sets A1:B1 bold. The two line amounts and total remain 75, 120 and 195.

  • Check ownership

    When comparing copies, focus the Macros dialog or editor on the specific workbook before drawing conclusions about its code.

Microsoft references

Continue practising: explore the existing Excel Task Hub for additional exercises.