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

12. Macros and VBA

Excel

12.4 The VBA Editor (VBE)

Aarti can run a macro from the workbook. When a teammate asks which cells it reads, she needs a place to see the program and try a small check. The Visual Basic Editor gives her a tree of open workbook projects, a code window and a place to inspect values. You will use each area with a short procedure on a training copy.

Connect the editor to your workbook

Open the right project before opening any code

Imagine an Orbit Logistics analyst building a pack total from a Swiggy-style delivery report. Orbit and the workflow are fictional, and the lesson does not describe any real business's own system. Aarti needs to confirm that the macro adds precisely two numeric amounts and writes only the chosen result cell. The test starts with 120 and 87. Those amounts add to 207, so an independent check is quick. She also keeps a short note on another tab so a wrong destination is easy to detect.

Project Explorer identifies EditorPractice, the Code window shows modReports, and the Immediate window shows 207.
Each editor area addresses a different question: where does the code live, what will it do, and what value did it calculate?
  • Visual Basic Editor: Often called the VBE, it is the part of desktop Excel where you inspect and edit VBA. Save your own blank practice workbook as EditorPractice.xlsm before adding code. Use Developer then Visual Basic to enter its editor. Alt plus F11 is a common Windows shortcut, while menu and keyboard behavior can differ on Mac.
  • Project Explorer: The tree lists loaded projects. Several open Excel workbooks, a personal macro workbook or add-ins can appear there at the same time. Find the entry with EditorPractice.xlsm in its displayed name. Expand the project instead of opening the first Module1 you see anywhere in the tree.
  • Objects and modules: Sheet and workbook objects have their own modules for code related to those objects. A standard module is a general place to store macros and useful helper procedures. For this routine create a standard module under your practice workbook. Later lessons can introduce event procedures that react to workbook or worksheet changes.
  • Code window: Double-click your module or use View Code. The pane shows declarations and procedures, and has a procedure list for jumping between them. Inspect both the active project and the code window to locate a particular instruction. Another workbook can have a module with the same name.
  • Properties window: When a module is selected, its properties include its name. In a standard module you can rename Module1 to modReports if that name is available. Check the selected object first. Renaming a standard module is different from renaming a worksheet tab or saving the workbook under a new filename.

Use the View menu if a pane is missing

The editor has its own menus and layout. If Project Explorer is hidden, use the editor's View menu to display it. The same approach locates Properties Window and Immediate Window. Some versions offer keyboard shortcuts, such as Ctrl plus G for the Immediate window on many Windows configurations. Use the visible menus when keys are remapped or hardware uses the function key row for other tasks.

When returning to Excel, switch back to the application window rather than assuming the workbook was closed. You can keep the worksheets and the code open together and compare them as you step. The code editor does not change the workbook type. Saving a project inside an XLSX file can still lose the code in that file even though the procedure was visible in the editor before saving.

Remember: Verify the workbook file in Project Explorer before typing. A familiar module or procedure name alone does not identify the owner.

Read the code before running it

Separate declaration, calculation and write

A declaration gives a variable a name and often a type. Placing Option Explicit before procedures in a VBA module requires every variable to be declared. That can catch a typo before a write takes place. In the editor's Options, the Require Variable Declaration option can add the statement when new modules are created. When maintaining an existing module, inspect its declarations and edit that module deliberately rather than assuming the editor setting went back and updated all earlier code.

  • Compilation: VBA checks whether the project can be translated into a form it can execute. For example it checks that a typed declaration is valid, a procedure is properly ended and names covered by Option Explicit are declared. Debug then Compile, in an editor version that offers it, is a deliberate pre-run check. The menu can be unavailable when no new compilation is needed or when the debugger is in another state.
  • Runtime: When the procedure is called, Excel has to find the actual workbook, sheet and cells. A correctly spelled reference in the code can still fail at runtime if the sheet is missing or protected. The compile result cannot prove the existence of the current worksheet or the values held there.
  • Business logic: A valid program can still add the wrong two inputs or place the answer in the wrong cell. That is why Aarti writes down 207 as her separate expected result. A direct comparison of B4, a check formula and an unrelated note reveals more than “compile succeeded.”

Treat a line in the Immediate window as executable

The Immediate window can show output from Debug.Print and evaluate an expression entered there. With a leading question mark it prints the value of an expression. Other lines can call procedures or perform actions. Here you will use small read-only expressions and inspect their results before editing the module. Name the workbook and worksheet in your expression because unqualified examples can refer to whichever workbook is active in Excel rather than the project that caught your eye in the editor.

While debugging, context can also depend on which procedure is paused. A local variable exists inside its procedure, and can be inspected in the relevant active context. If the procedure has completed, use your printed output and the worksheet instead of expecting that local variable to still be available. Later lessons show breakpoints and the Locals window with examples tied to one specific active run.

Lab one. Create a standard module and read the first result

Make the workbook before opening the editor

Use two separate test workbooks for the same four-row layout
CellPurposeEditorPracticeEditorImport
B2First source amount12050
B3Second source amount8760
B4Macro output207 after run110 after run
D2Independent sum formula207110

For the first lab use the EditorPractice column. In the workbook named EditorPractice.xlsm create two sheets named Practice and Notes. Add labels in A2, A3 and A4 to describe the two prices and the packed total. Enter the prices in B2 and B3, leave B4 empty and use the formula in D2. Use a short marker in Notes A1 such as “EditorPractice notes.” Put “Outside the result” in Practice C4 so you can confirm the write stayed on the chosen cell.

D2: =SUM(B2:B3)

Insert the right module and paste one procedure

  1. Open Developer Visual Basic. In Project Explorer select the workbook project for EditorPractice.xlsm. Choose Insert then Module. The new standard module should appear under Modules for that project. The project name might begin with VBAProject and show the workbook name in parentheses.
  2. Find the module's Properties window, check the selected item and change its name to modReports if available. When navigating the tree, double-click modReports to display its code. You can distinguish it from the sheet object called Practice. Open the style or test sheet in Excel, then return to the code window and verify both names again.
  3. Add the code below to the empty module. Use the editor's plain text view. If the module already begins with Option Explicit, keep exactly one copy above any procedures. Read the two Dim declarations for input values and the one for the calculated amount. Dim tells VBA which variables the procedure plans to use.
  4. Inspect the workbook's project and use Debug then Compile, if present. Save the XLSM workbook using Excel. Compile can find a misspelled name before runtime. It does not recalculate the practice sheet, so B4 remains blank after compilation. Read back D2 separately to verify the expected total before running.
Option Explicit

Public Sub PreviewPackTotal()
    Dim ws As Worksheet
    Dim firstAmount As Variant, secondAmount As Variant
    Dim packedTotal As Double

    Set ws = ThisWorkbook.Worksheets("Practice")
    firstAmount = ws.Range("B2").Value2
    secondAmount = ws.Range("B3").Value2
    If VarType(firstAmount) <> vbDouble Or VarType(secondAmount) <> vbDouble Then
        MsgBox "Enter two numeric amounts on Practice."
        Exit Sub
    End If

    packedTotal = firstAmount + secondAmount
    Debug.Print "Practice total", packedTotal
    ws.Range("B4").Value2 = packedTotal
End Sub
  • The worksheet variable: The procedure locates Practice in the workbook holding the code, independent of whether Notes is currently selected. The Set statement assigns a reference to the worksheet object. It does not change a worksheet cell.
  • The input variables: Range Value2 gives the cell's stored or calculated value. Using a Variant lets you inspect what type Excel returned. For this practice workbook Excel provides ordinary numeric cells as doubles. Text and blanks need a deliberate choice before trying arithmetic. A date serial still counts as an underlying number and needs a separate check of column meaning.
  • The numeric result: Two valid inputs produce a number in packedTotal. Look at where the procedure prints that number and where it writes it. The print line is useful for the person looking in the editor. The final assignment changes the workbook and gives the report user a cell to inspect.
  • The failure branch: If a value is missing, Excel should display the message and exit before the print and the write. A previous 207 might remain in B4. The Immediate window may also retain earlier output. Look for a newly printed line and check when it appeared. Choose the current run's message and state as the evidence.

View the result in three places

  1. In the editor, open Immediate from the View menu. Keep your modReports code visible too. In the Immediate window, evaluate the first two read-only lines below one at a time. Type or adapt the actual saved workbook name if Excel appended a number. The first should show two worksheets and the second should show 120. Use the project tree and filenames to identify the right copy.
  2. In Excel, select Notes and run PreviewPackTotal with the Developer Macros dialog scoped to EditorPractice. Check B4 on Practice. It should contain 207, matching the live formula in D2. Notes A1 and Practice C4 should retain their marker text. Open the editor and look for the newly printed Practice total and 207.
  3. In the Immediate window enter the remaining read-only line below to check the actual stored B4 result. Compare the three numbers, then clear the output manually in your practice sheet so you can observe the write once more. If you run under a debugger that pauses between the print and write, the new Immediate output can exist before B4 changes.
? Workbooks("EditorPractice.xlsm").Worksheets.Count
? Workbooks("EditorPractice.xlsm").Worksheets("Practice").Range("B2").Value2
? Workbooks("EditorPractice.xlsm").Worksheets("Practice").Range("B4").Value2

Read print and write separately: The line labeled Practice total is meant for a developer. The value in B4 is meant for the report reader. An Immediate expression asks Excel for the specific property at the moment you issue it. That can show it was written without changing the worksheet or selecting the cell.

Trace a successful editor cycle

  1. Locate the workbook

    Choose the EditorPractice project and its standard module. Confirm that the procedure and sheet names are the ones you wrote down.

  2. Check the declarations

    Option Explicit and the Dim statements define the names used by the procedure. Compile can catch a typo before you run.

  3. See what was calculated

    120 plus 87 gives 207. A new labeled line appears in Immediate after the procedure calculates the amount.

  4. Observe the worksheet

    B4 contains the stored 207 and D2 calculates 207 independently. The markers outside B4 are still there.

Lab two. Move one reviewed module into a separate workbook

Prove the module acts on the workbook that contains it

When you copy only a standard module, you transfer its VBA instructions. You have not copied worksheet data or the layout the macro expects. The receiver needs a matching Practice sheet with the input values and output cell in the right places. This exercise uses a different pair of amounts, 50 and 60, so it is easy to prove that the imported procedure uses its new workbook rather than the original.

EditorPractice uses 120 plus 87 for 207. EditorImport uses 50 plus 60 for 110 after the same reviewed module is imported.
The procedure keeps the same name and cell coordinates. ThisWorkbook changes when the code belongs to another file.
  1. Keep your passed EditorPractice.xlsm saved. Create a separate blank workbook named EditorImport.xlsm. Add Practice and Notes, enter 50 in B2, 60 in B3 and keep B4 blank. Enter the independent sum formula in D2. Give the new Notes marker text “EditorImport notes” so you can identify it by reading the sheet.
  2. In the editor tree select modReports under the source project. Use its Export File command if offered to save that one standard module as a local BAS file. Give it a distinct name and keep it beside your own disposable practice files. Review the source before transferring. A BAS export contains source code and can include module attributes. It does not include the worksheets that provided the input values.
  3. Select the EditorImport project in the tree. Use Import File and choose the reviewed BAS file if your VBE offers this workflow. Inspect the result under the destination project's Modules node. A supported alternative is to copy your reviewed VBA text into a new blank standard module in the intended workbook. This preserves the ability to verify the same example even when a menu differs by platform.
  4. Check Destination before you save. Compile the intended project, then open the Macros dialog in the destination workbook and select This Workbook. The same procedure name can appear in both projects when both files are open. Choose the one with the workbook containing 50 and 60.
  5. Run PreviewPackTotal in the destination copy, if permitted. The imported code's ThisWorkbook now points to EditorImport. B4 in EditorImport should become 110 and match D2 there. Inspect B4 in EditorPractice independently and expect it to remain 207. Saved notes in both workbooks keep their own exact contents. This is the proof of the module scope.

You can repeat the comparison without switching worksheets in Excel by using read-only expressions with explicit names in the editor. Enter the lines one at a time and match each result to its workbook name. Workbooks must already be open in the same running desktop Excel session for these expressions to retrieve them. The statements read the property directly. They do not write new values.

? Workbooks("EditorPractice.xlsm").Worksheets("Practice").Range("B4").Value2
? Workbooks("EditorImport.xlsm").Worksheets("Practice").Range("B4").Value2

Compare a compile problem and a runtime problem

  1. Check a spelling failure in a separate practice copy. Copy the approved exercise workbook with an unmistakable filename before editing. In its module change the calculation assignment's variable name from packedTotal to packdTotal without changing the declaration. Use Debug then Compile. Because Option Explicit is present, VBA should identify an undeclared name. You can observe that diagnostic without running the macro. Restore the spelling and compile again.
  2. Check a runtime input failure. In the imported workbook's Practice sheet clear B3 and keep B4 at its last result, 110. The current D2 formula is now 50. Run the macro in that practice copy. Expect the named validation message and no new successful print for that invocation. The old amount in B4 should not be used as a total for the changed data.
  3. Restore the approved fixture. Return B3 to 60 and run again. Check the printed and worksheet amounts. If you experimented with a temporary copy or exported file, close it or leave it in a separate practice folder. Keep the original workbook and the destination exactly identified in your learning notes.

Explain both outcomes: An undeclared name is a source-code error and can be caught before the run. An empty or text source cell is a data state recognized by the program when it executes. The two branches have different evidence and different fixes.

Resolve editor problems with one precise observation

Predict where the editor should lead you

  • No project visible: Use the editor View menu to show Project Explorer. Check that your practice workbook is open in Excel. If the environment is browser-only, the desktop VBA editor is not part of that browser session. Use the code and worksheet trace on the page.
  • Blank code window: Expand the correct project to Modules. Double-click the specific module to see its contents. A sheet's module can open empty even though the standard module contains your procedure. The editor tree and selected pane identify different things.
  • Duplicate name: A module or procedure may already have the name you chose. In one project avoid importing a second copy of the same callable code. Compare existing module names, procedure names and which version is the intended one. Keep an exported copy separate from the open project before replacing anything.
  • Compile menu unavailable: The editor may already have a compiled project or be busy in a paused execution. Return to your expected project and the appropriate design state. A currently unavailable command is not an output from your test procedure. Use the correctly saved project and verify your lab test when code edits are finished.
  • Immediate has old messages: Scroll to the latest output and note the data you just changed. Print a recognizable label in your own module. A message from EditorPractice can sit near one from EditorImport when both have run. Confirm the worksheet result by naming the workbook in your read-only test.
  • Result is saved in the wrong file: Check which project held the code and the destination the procedure named. If the original still shows 207 while your import shows 110, both acted as intended. If the wrong workbook's note or B4 changed, inspect the macro scope and restore a known clean copy rather than guessing at another run.

Record three kinds of evidence in your notes

Write one line naming the project and standard module, one line showing the numeric input with the procedure's output, and one line showing an unchanged cell. This is enough to explain a transfer to somebody who never saw your editor window. You can add the exact source and destination filenames so they reproduce the action without accidentally targeting your original. Keep the isolated code and test sheet together when sharing an exercise through an approved teaching workflow.

On a project with several procedures, one typo elsewhere may prevent compilation even though your change is correct. Read the full diagnostic and go to the highlighted module to understand which source file has the undeclared name. For a first lab keep the scope small by using a new disposable workbook. A short clean project makes it possible to learn what a compile problem looks like before facing larger reports.

Pause for a source check: Point to the exact line that can change the workbook and the exact line that can display a diagnostic in the editor. If a teammate says “I saw 110 in Immediate,” ask how they know which workbook owns that value and which cell now holds it.

Read the dependencies before sharing a module

Follow three references from the source

A dependency is something a procedure needs to work, such as the existence of a named sheet or another module. Importing only the code can succeed even if the destination lacks that requirement. In this lesson the standard module depends on a Practice worksheet and two valid numeric inputs. It reserves B4 as output. D2 is an independent check and is not read by the macro. Notes is evidence for your test and does not affect the calculation. These are five different reasons for mentioning workbook cells in the teaching text. Only B2, B3 and B4 appear in the code.

  • One sheet name: In the code window, read ThisWorkbook.Worksheets("Practice") as a workbook qualifier followed by a sheet lookup. The string matches the visible worksheet tab. Changing the tab to a new name does not automatically edit this string. If a second workbook is a template with a different tab name, create the documented tab in the lab copy or deliberately adapt the code and rerun your tests.
  • Two inputs: In the procedure Range("B2") and Range("B3") belong to ws. If a template owner inserts a row, formulas on the sheet may follow the inserted cells while the strings in code still refer to B2 and B3. A failed type check is one possible result. Another is the more confusing case where the two cells remain numeric but represent the wrong amounts.
  • One destination: Before running the module on an unfamiliar layout, find out what is already in B4. Our practice uses that cell for the packed total. In a workbook with a formula or another analyst's field there, a direct value assignment could replace it. A copy gives you a place to check the destination and learn the behavior with no need to experiment on a working file.

Compare the workbook's sheet module with a general macro module

Project Explorer often shows a sheet entry with an internal code name and its tab name. The project also has a workbook object entry. You can place some kinds of VBA in those object modules. For example, a worksheet event may run in connection with a worksheet action. This lesson's PreviewPackTotal is deliberately called by the user and has no event trigger. Put it in a standard module so you can find it by name in the Macros dialog and move it on its own for the second exercise.

A standard module can hold several related procedures. The name modReports tells a maintainer where to look, but a menu or user assignment generally selects the procedure name. Changing only the module name while working in another project can still be misleading. Open the intended file before editing. On a larger workbook, read a procedure's calls to other modules, forms or referenced libraries when preparing to copy it. Sharing one BAS file does not automatically transfer those other requirements and it does not transfer your training data. Give the exported module a version label in your notes so the receiver can identify the exact reviewed file before importing it.

Give a teammate a reproducible editor report

Suppose the archive team has an unrelated open workbook called HistoricalOrders.xlsm when you ask them to run your sample. It has a different sheet count and a sheet called Practice. An unqualified Immediate command for the worksheet count can show the result from the active workbook. Rather than asking them to close all files before they report a count, qualify the query by workbook name and identify the same project in the tree. If a file with the expected name is not open in that Excel session, the query can fail. The team should check the workbook name and save state rather than paste a different expression they do not understand.

Give a maintenance report with the workbook file and code module, app platform, expected input and exact observed result. For example, “In EditorImport.xlsm, I opened modReports in its own project, ran PreviewPackTotal through This Workbook, and read 110 in B4 from inputs 50 and 60. The original still read 207.” If a value changed, find the matching result with the independent formula and the explicit read-only query. This is more reproducible than “the macro worked on my screen.”

Explain why the independent check disagrees temporarily

Take the EditorImport copy after it passes with 50 and 60. Change the amount in B3 to 65. Under ordinary automatic calculation D2 becomes 115, but B4 still contains the stored 110. Both results have clear origins. The worksheet formula recalculated from the new data, and the stored output came from the preceding run. Read both using a qualified Immediate query or the worksheet. Then run the correct macro explicitly. The new printed line and B4 should now both show 115. B4 in EditorPractice should still be 207 throughout.

If a teammate says they see 110 in Immediate after the new run, have them name the cell they are inspecting. They could be looking at an old line even though the new 115 appeared further down. The read-only query for EditorImport B4 returns the currently stored result. A query for D2 gives the worksheet check. If the reference names EditorPractice instead, it belongs to a different workbook even though the tab name is identical. Record the intended filename, query and value together.

Once this test makes sense, change B3 back to 60 and run again. Expect 110 in the destination and 207 in the source. Keep both Notes markers. That tiny round trip tests your assumption about workbook ownership more precisely than three runs giving the same totals. A pass lets you explain what happened after the transfer and why code that uses a fixed workbook filename would need a different reuse strategy.

Separate syntax feedback from the data problem

Test the three familiar outcomes in your notebook before handing the file to someone else. In a clean copy with the undeclared name, the compile diagnostic highlights the code problem. In a valid copy with no second amount, compiling succeeds but the runtime guard warns and leaves B4 unchanged. In a valid copy where someone changes the calculation to add B2 twice, both source cells still pass the type check and the procedure runs, but the first result becomes 240 instead of 207. An independent formula shows that mismatch. Keep the original code intact and treat the third case as a paper exercise for source inspection.

Quick checks

Use the correct pane and workbook

Two open workbook projects have modReports. How do you choose yours?

Read the workbook name next to the project in Project Explorer. Expand that particular project to find the module. A single module name can exist in different projects. Confirm the procedure belongs to EditorPractice when using its two source values and to EditorImport after transferring it.

What happens when Option Explicit finds a misspelled variable during compile?

VBA identifies a variable that has not been declared. The code needs to be corrected before running the practice procedure. Compare the actual spelling in the declaration and assignment. Compiling this example does not put a value into the workbook, so a blank output stays blank until a permitted run.

Where should you find the text printed by Debug.Print?

Look in the editor's Immediate window. It can contain lines from multiple runs. Read the newly printed label and amount, then compare B4 and the independent D2 formula. Writing a line in Immediate does not itself write an Excel cell.

Does exporting modReports export the worksheet with it?

A standard module export contains VBA code and module information. Practice, Notes and their values belong to the workbook. When importing the module, create the matching sheet and populate the expected cells independently. Rechecking 110 in the new workbook and 207 in the original verifies that they provide separate data.

How can a macro show 207 in Immediate before B4 changes?

VBA executes the print statement before the assignment to B4. While paused after the print and before the write, the visible log can be ahead of the worksheet. The sample also has an independent worksheet output in D2. Check the execution position before treating all three values as current.

What does opening the editor while Notes is displayed do to this macro's write destination?

The destination remains Practice B4 in the file containing the code. It is set by the worksheet object and the chosen range. The current view may help you record a manual test, but it does not rewrite the qualifier used to find Practice.

Interview and discussion

Explain the most useful check for each symptom

Why use a standard module for a first workbook macro?

It gives you a clear place for a deliberately invoked routine and ordinary code you can inspect and share with a practice workbook. Excel can present a public no-argument Sub from a standard module to the operator. An object module is useful for different purposes such as events tied to a worksheet or workbook.

What is the difference between compile, run and verify?

Compile checks the code's structure and declared names. Run supplies actual input values and performs instructions like a worksheet write. Verification compares the result from that run with independent expected values and observes nearby cells. A procedure can compile and run successfully while still giving an incorrect sum for the underlying question.

How do you inspect a cell without asking a developer to select it in Excel?

Enter a read-only expression in the Immediate window. Qualify the open workbook, expected worksheet and cell, then print its Value2 with the question mark. Write down the original workbook name and the retrieved value. That allows the next person to repeat the check when another worksheet is displayed.

How would you check that ThisWorkbook changed during a module transfer?

Set matching layouts with distinct numeric inputs in the source and destination. The routine should write 207 in the source and 110 in the destination after executing the corresponding procedure in each workbook. Read both cells by workbook name. Distinct result values make a scope error easier to detect.

What would you do after seeing an old success line and a current missing-data message?

Treat them as evidence from different runs. Inspect B2 and B3 and verify that the current missing value triggers the guard before the print and write. The existing B4 result can still belong to the earlier successful state. Restore a genuine numeric amount or report that the present run has no accepted total.

Six recall cards

  • Project owner

    Find the workbook name in Project Explorer before selecting a module or comparing a procedure.

  • Standard module

    Insert a standard module for a routine a user will invoke. It can be exported and imported independently of worksheets.

  • Explicit declaration

    Option Explicit requires variable declarations. Compile can identify an undeclared name before the procedure changes anything.

  • Immediate trace

    Debug.Print shows a developer diagnostic. A question-mark expression prints the value currently read from its object.

  • Proof in two files

    The example uses 120 plus 87 in EditorPractice and 50 plus 60 in EditorImport, giving 207 and 110 in their own B4 cells.

  • Outcome evidence

    Check a formula, a macro result and an unchanged marker. Each answers a different question about the current run.

Microsoft references

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