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

17. Interview Questions and Answers

Excel

17.7 Macros and VBA Basics

Practise precise answers about recording, writing, debugging and sharing VBA. These two dry-run labs use a small fictional file and read-only diagnostics so you can demonstrate reasoning even where policy restricts macro execution.

Q55. Describe a macro and the workbook that owns it

Identify the repeated task and its permitted area

A VBA macro can run a sequence of instructions in a supported Excel desktop environment. It can automate repetitive work such as formatting a known header or reading an order list. In a fictional Amazon-style packing exercise someone repeatedly makes the order dispatch header bold. A macro can perform that one operation on the agreed cells. A formula instead calculates a value presented in a cell. Explain the real effect of the example, which workbook and worksheet supply the inputs, and which cells, if any, the macro changes.

A common way to preserve VBA in a workbook is to save it as an Excel Macro-Enabled Workbook with .xlsm. An ordinary .xlsx file does not store a VBA project. Other Excel formats can store macros too, so explain .xlsm as the practical choice for this local exercise. Record where the code is stored. Code saved in a personal macro workbook does not necessarily travel inside the training workbook you send a colleague. The developer environment, authorised code location and Excel client affect whether the recipient can invoke it. Check the actual workbook and do not infer active automation from a filename.

Know which environments are useful for a demonstration

Excel for the web can work with a workbook carrying VBA content, but Microsoft documents that VBA macros cannot be created, run or edited there. Desktop Excel versions supporting VBA can run an authorised macro in the intended environment. Some platform features differ, such as certain Windows-specific controls and paths. If the interviewer only provides web Excel or policy prohibits running a macro, use the dry run and explain the steps with a printed or on-screen copy. You can demonstrate object scope, expected results and error handling without weakening any settings.

  • State the business task first, then identify the code and workbook owner.
  • Describe which worksheet and cells a normal run would read or change.
  • Check that the format preserves the code before promising a transferable workbook.
  • Use a disposable practice copy, code you reviewed and an authorised runner.

Q56 and Q57. Explain a recorded action and its dependency on selection

Compare recorder output with a reviewed macro

The recorder translates supported Excel actions into VBA instructions. It is useful for learning the object syntax and capturing a repeatable short sequence. A recording may omit the reasoning behind the clicks and can rely on a current selection, worksheet or workbook. Hand-written VBA can qualify the destination, check for expected inputs, handle empty data, loop over known records and report an unexpected state. That flexibility does not make it safe for arbitrary workbook sizes or structures. Check documented prerequisites and the exact intended range.

A recorded action can identify an absolute address. For example, a pattern ending at Range("C2") targets C2 in its current sheet context. A relative recorded action can move one column to the right of the current anchor with an offset. The same starting cell B2 makes both examples target C2. Starting from D4 exposes the difference. The fixed address targets C2 while the one-column-right offset targets E4. Inspect the actual generated code because recorded instructions may contain several selections, references and other dependencies. Shared code should express the intended workbook and sheet contract explicitly.

Both approaches target C2 starting at B2. From D4 the fixed target stays C2, while an offset one column right targets E4.
A second starting cell reveals whether the address or the local movement was recorded.

Lab one. Predict both requested targets before an authorised rehearsal

Use a throwaway workbook or a paper grid. Write C2 and E4 as two distinct target cells and keep an unrelated note in B2. In a supported desktop Excel and authorised practice session, the optional recording exercise can make an agreed test cell bold. The core lab is a dry run and requires no macro permissions. Read these illustrative address expressions and identify their actual target. The expressions show the addressing choice, and are not stand-alone runnable procedures.

ws.Range("C2")
ws.Range("B2").Offset(0, 1)
ws.Range("D4").Offset(0, 1)
  1. For a fixed-report task select the worksheet identified as the authorized report. Predict C2 for the first expression even if a user has highlighted D4. Qualifying the expression through ws defines the sheet. It must refer to the worksheet planned by the author.
  2. In the second expression start at B2. The zero row offset stays on row two and one column right moves to column C. Write the observed target C2 in a worksheet note or on paper.
  3. In the third expression start at D4. The same movement reaches E4. This is appropriate when the business authorizes a small change relative to a validated starting point. A user clicking a different location before running relative code changes that anchor.
  4. Test a right-edge case. Offset one column from the final worksheet column has no valid destination. A robust written routine would check the permitted target before using such an offset. The original fictional report changes neither the note in B2 nor cells outside the agreed target.
  5. If you optionally record a formatting change in your own scratch workbook, check which procedure is generated, inspect the target for a second starting location, and restore the initial formatting or discard the copy afterwards.

Explain how moving to a wrong sheet could be worse than a wrong cell

Imagine two workbooks have a Report tab and C2 is a real business figure in one. A macro without an explicit scope could format or overwrite an unintended report if another file becomes active. Using a known workbook and sheet object addresses the ambiguity. ThisWorkbook identifies the workbook containing the VBA code. ActiveWorkbook refers to the current active workbook, which depends on user context. If the macro lives in a personal workbook but needs to act on a separate open file, using ThisWorkbook alone selects the wrong owner. In a shared process apply an explicit selection and qualification rule and verify the object properties before writing anything.

Interviewers may ask whether an absolute or relative recording is better. Answer with the task. If an authorised sheet always has the same header location, a fixed address is simple and can be qualified to that sheet. If the task formats the next cell for a user-provided anchor, an offset can express the movement and should be bounded. In both cases test a second context and a verified unaffected area. The two patterns describe functional requirements, not a global speed or quality ranking.

Q58. Explain what last row means in one column

Distinguish final occupied row, row count and valid records

The common last-row expression starts at the last possible cell in a chosen worksheet column and moves upward to the end of its region using End(xlUp). A typical input with header in A1 and final record in A5 yields row five when starting below the data. This is a worksheet row number. It does not count records and cannot decide whether a value is an approved identifier. A blank key row can appear internally. A cell containing a formula can be occupied even when it shows empty text. A formatting change to a distant cell can affect some used-range methods without representing a key. Name the column and meaning before giving a last-row answer.

Check the edge cases. A sheet whose last allowed row already contains data needs an explicit check before the common upward move. A header-only A1 means there are zero data rows even though the last row reported is one for that input. A blank entire column also needs an independent header or source check. A note on B9 begins a different scope. If the source is an Excel Table, ListRows.Count reports its number of data rows and does not count the header or optional totals. A blank-labelled Table member can still contribute to this row count. Verify a key if the count needs to describe valid orders rather than worksheet members.

The procedure addresses Orders in the owning workbook. Column A ends at row five and contains 3 nonempty text keys below its header.
In the scratch dataset the highest occupied position is five, but the simple text-key count is three.

Lab two. Read the target and trace the expected diagnostic

Use your own scratch Orders sheet with A1 equal to Order ID. Enter BOX101 in A2, BOX102 in A3, leave A4 genuinely empty and enter BOX103 in A5. Put the literal unrelated note in B9. The checked input policy here counts nonempty text below the header. It does not infer uniqueness or check an official format. An interviewer can ask for those business checks next. The following VBA reads the column and writes a short diagnostic to the Immediate window. Review its logic even if you cannot run it under your local policy.

Option Explicit

Public Sub ReviewFootprint()
    Const ProcedureName As String = "ReviewFootprint"
    Dim ws As Worksheet
    Dim bottom As Long
    Dim lastRow As Long
    Dim recordCount As Long
    Dim i As Long
    Dim rawValue As Variant
    Dim failureNumber As Long
    Dim failureText As String

    On Error GoTo Failed
    Set ws = ThisWorkbook.Worksheets("Orders")
    If CStr(ws.Cells(1, 1).Value2) <> "Order ID" Then
        Err.Raise vbObjectError + 401, ProcedureName, "Expected Order ID in A1."
    End If

    bottom = ws.Rows.Count
    If IsEmpty(ws.Cells(bottom, 1).Value2) Then
        lastRow = ws.Cells(bottom, 1).End(xlUp).Row
    Else
        lastRow = bottom
    End If

    For i = 2 To lastRow
        rawValue = ws.Cells(i, 1).Value2
        If VarType(rawValue) = vbString Then
            If Len(Trim$(rawValue)) > 0 Then
                recordCount = recordCount + 1
            End If
        End If
    Next i

    Debug.Print "Orders | last row " & lastRow & " | text keys " & recordCount
    Exit Sub

Failed:
    failureNumber = Err.Number
    failureText = Err.Description
    Debug.Print ProcedureName & " stopped (" & failureNumber & "): " & failureText
End Sub
Expected diagnostics from separate scratch variants
InputLast rowText keys
Baseline A2, A3, A553
Add BOX104 at A884
Empty-text formula at A883
Header only10
  1. Trace the object assignment and checked header. In an authorised scratch project the procedure belongs to that workbook. Its target is Orders anywhere in that workbook's tab order.
  2. Predict the first diagnostic. Cells in B cannot extend the A column result. A4 fails the text predicate while A2, A3 and A5 pass. The loop stops after row five and reports three.
  3. Use separate copies for A8 containing BOX104 or a formula returning an empty string. Both are occupied positions. The former adds a text key. The latter produces zero-length text, so the count stays three although the row boundary becomes eight.
  4. With only the valid header left, last row is one and a positive-step For loop from two to one does not execute. Expect zero. Lookup or header failures instead use the diagnostic path. An absent Orders sheet or the wrong A1 heading must stop before a success message.
  5. Confirm the note B9 and all source cells are unchanged. The example uses no worksheet writes. Reset the fixture or discard it after testing, and retain the expected diagnostic separately.

Q59. Choose a Sub or a Function by the interface it needs

Describe the procedure's effect and returned value independently

A Sub represents a procedure that performs work and does not return a value as an expression. A public no-argument Sub in an appropriate module can be an entry point in the macro dialog in a supported environment. ReviewFootprint is a diagnostic Sub. It reads its source and writes a short debug message. Another subroutine could format cells. The choice of Sub tells you about the procedure interface, so inspect the body to know what it actually reads or changes. A Function returns a value to its caller through the function name assignment. A worksheet-callable custom function can calculate from supplied arguments, subject to restrictions on workbook state changes.

Contrast a returned amount with a display operation. Suppose the training partner charges fee 30 on a nonnegative amount below 99, and fee zero from 99 onward. A small function could return a number for the applicable band. It should have no need to format the cell, change the sheet's column width or update the workbook outside the caller's result. If you want to style the result, use a cell format or a separate authorised procedure. Give a value such as 98 yielding 30 and 99 yielding zero to demonstrate the boundary. A well-explained function also documents what happens to unsupported data.

Public Function PracticeDeliveryFee(ByVal amount As Double) As Variant
    If amount < 0 Then
        PracticeDeliveryFee = CVErr(xlErrNum)
    ElseIf amount < 99 Then
        PracticeDeliveryFee = 30
    Else
        PracticeDeliveryFee = 0
    End If
End Function

On a scratch sheet, or as a paper dry run, compare =PracticeDeliveryFee(98) and =PracticeDeliveryFee(99) to the intended numeric outputs. For negative one, the sample deliberately returns an Excel numeric-domain error. It uses a numeric procedure argument for a checked numeric-call example. If consumed from a source that includes blank or text inputs, validate them in the caller or design and test a function that handles those cases explicitly. Worksheet and VBA conversion at the function boundary can change what an untyped value becomes. A result of zero means no practice fee at a valid threshold, while an error indicates the input was outside the taught policy.

Explain inputs passed to a procedure

In a written interview exercise, an argument can describe a value or object the caller supplies. The amount parameter of PracticeDeliveryFee is declared ByVal, so changing that variable inside the function would not change the caller's scalar argument. Some Subs can receive arguments as well. Saying that a Sub "does something" and a Function "calculates" is a helpful beginning, but a more precise answer gives the return interface and whether a worksheet-callable function has side effects. State the exact allowed workbook changes before reusing any procedure in someone else's file.

Q60. Report a failure and restore only the state you changed

Plan the exit before writing the main processing

In ReviewFootprint, the On Error GoTo instruction identifies a local error handler. A missing Orders worksheet raises a runtime error when assigning ws. A different A1 header triggers an explicit Err.Raise to make the failure readable. The success path exits before falling through to the handler. The handler captures the number and description promptly and prints the diagnostic. The lower-level error should be available to a reviewer. Since this routine only reads cells, it has no application state to restore. Do not add a global switch simply to demonstrate cleanup.

Some procedures change application properties in order to execute an authorised operation. For example, a procedure can temporarily alter ScreenUpdating. Its cleanup needs to restore the actual prior state rather than always setting it to True. Another routine may have already set it to False for a legitimate reason. Save the value before changing it and restore it in both normal and exceptional paths when you can do so safely. Capture error evidence before cleanup calls that could fail or alter Err. A successful restore of a global setting will not reverse edits already written to worksheets. Plan prevalidation and a bounded write separately.

On Error Resume Next can be used narrowly where a particular failure is expected and immediately inspected. More broadly suppressing errors can leave a partly completed result. A missing optional item is a case to handle explicitly. A missing required sheet is a case to stop. If using a local suppressed block, inspect Err.Number and relevant values at once and restore the intended error handling for the code that follows. Use the documented On Error GoTo 0 to disable the current procedure's active enabled handler when that is the intended state. Keep the examples small so the scope is apparent to an interviewer.

Test failure independently of the success case

  • Missing source. On a disposable version temporarily rename Orders. The object lookup fails and ReviewFootprint reports a stop. The business check is that there is no success count and no worksheet changes.
  • Wrong structure. In another reset copy replace Order ID in A1 with a different heading. The code raises Expected Order ID in A1. A source field can be missing while a sheet name still appears correct.
  • Blank valid source. In a reset copy keep the validated header and remove only the three practice keys. The diagnostic stays on the success route with row one and zero keys. A valid empty dataset is distinct from a failed structure.
  • Cleanup. Restore the original file or discard the deliberate test copies. Avoid recording entire business rows in diagnostic output.

Trace a refused workbook without touching data

  1. Identify the owner

    The macro binds to Orders in the workbook containing its code.

  2. Read the first expected field

    The baseline header is Order ID. The deliberate variant has a different label.

  3. Follow the failure route

    The procedure raises a clear diagnostic. It has not entered the record loop.

  4. Check the evidence

    Look for the stopped message and verify the sheet's source values and the unrelated note remain unchanged.

Q61. Inspect what the program knows at the moment it differs

Use a breakpoint before a controlled operation

A breakpoint pauses execution before an indicated code line. Step Into can advance the next statement in order in the Visual Basic Editor. Common Windows keys include F9 to toggle a breakpoint and F8 to step into; consult the editor's Debug menu if the host uses a different key mapping. On an authorised scratch workbook place a breakpoint on the start of the loop before executing any side effects. In this example inspect the lastRow and current index. At the first record i is two, the source shows BOX101, and the count should become one after the condition passes.

Locals helps examine values in the current procedure, Watch can follow a chosen expression and the Immediate window can display Debug.Print output. The Immediate window can also execute statements, so use a planned passive inspection in the rehearsal. A Watch item should concern a safe value, such as the current row number. Avoid invoking actions or inspecting confidential real data while screen sharing. Use Option Explicit before module procedures so undeclared names are caught as the project compiles, and check expected types when reading cell values. It does not verify the data rule or guarantee there are no logic errors.

Walk a test into concrete observations

For the baseline with keys at rows two, three and five, the count goes one, two, stays two at row four, then goes three. A long worksheet extension at A8 can add a populated cell while intermediate blanks do not add text keys. If the code used the number of loop iterations to infer orders, it would report four in the baseline from positions two to five. If it used sheet-wide UsedRange as the count, the B9 note could disagree with the chosen key column. By stopping at the first wrong value you can identify which implementation answered the wrong question.

A compile error is an issue before a successful run, such as an incorrectly declared variable or malformed statement. A runtime error occurs during execution, such as looking up an absent sheet. A logic problem can give a plausible number with no VBA error. In an interview give one example of each. Then say which controlled input or inspection would isolate it. If the VBE stops, verify whether the highlighted line is about to run or reflects an exception before drawing conclusions from values in scope.

Q62. Diagnose a recipient's workbook without changing their security policy

Separate availability, file identity and runtime behavior

A colleague may be viewing a workbook in Excel for the web, where VBA macros cannot run. The workbook may have been saved in a format that does not preserve the project. Their device may enforce rules blocking macros from an untrusted source or require an approved signed solution. Microsoft documents Windows policies for files from the internet, and organizational policies can specify which code is permitted. Ask for the exact environment, file type, authorized source and prohibition before changing the code. Use the approved IT process if execution is disallowed. The lesson never requires unblocking an unknown downloaded file or weakening security.

If execution is permitted and the macro starts, inspect the exact object it expects. A missing worksheet, inaccessible path, incompatible control or different layout can produce a runtime failure. A training macro taking its source from an explicit Orders worksheet can say which required field was missing. A record of the file owner, key header, authorised output and client version makes that report actionable. In a shared environment a second person's copy may contain the same sheet name and a different schema. Test representative authorized copies before promising broad support.

For a live demonstration choose a scratch workbook with a small known dataset and no external credentials or data. Show the procedure and one predicted outcome if the recipient can follow it. If the approved environment cannot run the code, present the exact expected messages from the dry run and describe which checks you tested independently. A reviewer's authorization is required for real distribution or changes. A macro that simply does not run may be behaving correctly when policy blocks it. Report the state rather than bypassing it.

Describe a handoff someone can reproduce

Include the workbook format, module and procedure name, exact source worksheet, required field and expected result. State whether the procedure writes anything. For the read-only diagnostic, include the baseline last row five and three nonempty text key cells, then a test with one empty-text formula at row eight. Give the outcome you actually observed in the approved environment and state separately which cases you modelled. Practice evidence can be useful without claiming workplace automation experience or successful production execution.

  • Check whether the recipient has standalone supported desktop VBA access.
  • Verify that the code exists in the intended workbook project and required source sheet.
  • Review source and maintenance ownership before moving a workbook to shared spaces.
  • Record workbook or error identifiers that a reviewer can use without posting confidential content.

Quiz. Predict the exact trace

Which formats are relevant to the practice code?

Save the local practice workbook as an .xlsm if the VBA project must accompany it. An .xlsx cannot store the VBA project. Verify that the code is in the expected workbook's module and that approved execution is available.

If the starting point changes to D4, what do the two targets become?

The fixed address still targets C2 on its qualified worksheet. One column right of D4 is E4. Use the second start to detect the dependency on the anchor.

What are the baseline row boundary and text key count?

The boundary in column A is row five. There are three nonempty text keys below the header. The note in B9 is outside this scan and the blank A4 is not a valid key.

What changes if row eight contains an empty-text formula?

The occupied boundary becomes eight. The formula returns empty text, whose trimmed length is zero, so the key count remains three. This verifies the difference between worksheet occupancy and a business test.

What does the procedure do if A1 is wrong?

It raises a specific error, enters its handler and reports the diagnostic. It skips the success record and leaves source values untouched. A valid header without records is a different successful state.

Will a blocked macro in web Excel require relaxing macro settings?

Web Excel does not run VBA. Confirm that the user has an approved compatible environment. Continue the dry run when an authorised execution path does not exist.

Model answers for automation follow-ups

Why record first and write manually later?

I use a recorder to learn how a supported action maps to VBA. I then inspect selections and ranges, qualify ownership and check the input contract. I test the intended output on a fresh example and verify cells outside the permitted scope.

How do you find a last occupied row without treating it as a count?

I choose a key column and qualify the sheet. I check the worksheet's final possible cell before applying the usual End(xlUp) from below, then test the head-only or blank cases. In the fixture A5 is the boundary and three approved text cells qualify.

When would you choose a worksheet function instead of a macro Sub?

I use a function when a worksheet expression needs a returned value, such as the delivery fee. I verify numeric and boundary inputs and keep it free of extra workbook changes. A formatting action belongs in a separate authorised procedure.

How do you handle an error without losing useful evidence?

I use a narrow error handler, preserve the error number and description, and restore any earlier settings I intentionally changed. The startup guard checks an expected sheet and header. I test that invalid input stops before a success announcement.

How can you hand over a test that a reviewer can repeat?

I give a scratch dataset, the specific entry point and known results for normal, empty and invalid inputs. I note platform and execution policy. I then check both the reported output and that unrelated source cells stayed unchanged.

Recall cards

  • Workbook ownership

    ThisWorkbook identifies the code's workbook. Qualify the intended worksheet and range.

  • Absolute and relative

    A fixed reference keeps its address. An offset starts from the stated anchor.

  • Row boundary

    Largest occupied row depends on the chosen column. Valid key count has its own rule.

  • Procedure contract

    A spreadsheet function returns a value. A Sub is a procedure with no returned expression value.

  • Error evidence

    Record the error and restore genuine prior state when your code changed it.

  • Trusted environment

    Check supported client, workbook format and approved execution before a rehearsal.

Official references

Defend the same workbook when a follow-up changes the input

Check what the existing loop calls a record

The practice only counts nonempty string cells. Add numeric 104 at A8 in one scratch copy. Its worksheet position is used, so last row is eight. It is stored as a number, so VarType does not deliver vbString and the result remains three. In another test enter a quoted text ID 104 through Excel's text entry mechanism or preformat its input as Text before entering it. The string is nonempty, so the count becomes four. Both cells can appear to show 104. Use the underlying type in the explanation and decide which format the source contract requires. If a workstation exported real identifiers as numeric values by mistake, the diagnostic can reveal that mismatch without changing the source.

Try entering BOX101 again at A8. The simple text count becomes four, but only three distinct original keys exist. A distinct-key requirement belongs in a deliberately chosen validation or data preparation stage. You could collect encountered keys in a suitable structure and report duplicates before using any count in a publication. Check whether case and leading zeroes are significant. A practice count that says "three nonempty text cells" can be correct while another claim about "three unique authorised order records" remains unverified. Use the exact name of the observed measure.

There is another useful coverage test. Put a blank-looking formula in A8 and a genuinely populated cell in B9 as instructed. The column-A point still ends at row eight. A programmer who changes the rule to test formula presence could count the cell differently from the required text input. Walk the source through the conditional check and watch both lastRow and recordCount. The former is observed once before the loop. The latter increases only when both conditions are satisfied. Those two pieces of state respond to different facts.

Explain a faster design without promising a dead-simple replacement

Iterating over the worksheet one cell at a time is understandable for five rows and useful in an interview dry run. A much larger authorised table may benefit from reading a checked rectangular source into a Variant array and examining it in memory. A normal multicell Value2 read produces an array for a contiguous rectangular range. A single cell produces a scalar, so a replace-in-place design needs a deliberate one-record path. A source with no rows should avoid reading an absent data body. Set a known input shape and test all three counts before using a faster loop on a larger copy. Verify that the expected record policy stays the same.

If sharing the script across multiple workbooks, pass the approved worksheet object or use an explicitly validated workbook and sheet selection rather than guessing from the current view. A runner named ReviewFootprint can establish that input once. A separate function can take the source array and compute simple statistics, then return them without the workbook dependency. An interview answer should explain why that structure helps isolate test inputs. It also needs to explain a failure case seen before doing any actual sheet changes. Avoid extending the simple training routine merely to show advanced syntax.

Show an appropriate repeat before adding writes

Run a dry trace twice against the same baseline and predict the identical print message each time. It has no workbook effect, even though the debugger can show two messages. Imagine a proposed extension writing the result to a report cell. Identify the exact approved output range and who owns it. If it appends on every run, executing twice could create two conflicting records. A review record may intentionally preserve each execution, but it then needs a batch ID and an agreed audit design. A fixed practice result can instead update an agreed named location. Test that the second run has the intended effect, and check that the B9 note was never inside its range.

Failures matter before and after writes. Before a write a missing input should stop cleanly. After a partial write a handler can log an error, while the file might contain an incomplete result. A stronger design stages and validates the data first, writes a known output block, and checks it afterwards. If the write still fails, explicitly identify which workbook and output need review. Restoring screen updates only affects display behavior. It cannot prove that an earlier workbook edit was rolled back. This is a common follow-up when automation is applied to a daily shared report.

Avoid broad workflow claims when giving a beginner answer

Do not say that a macro works on any machine unless you have established the platform, workbook structure and approved security context. State the conditions for the particular exercise. A supported desktop Excel instance, a local disposable .xlsm, an Orders sheet and expected heading make the target concrete. The read-only code relies on no network path or Windows-only control, while the approved user still needs VBA access. If the conditions are absent, state the reason the outcome is pending and use the documented static exercise. Restore or discard examination copies according to the agreed practice workflow.

When reporting the result, connect every observation to the exact source file. A valid workbook opening in the web proves the workbook is readable in that client. It does not prove something happened in the VBA project. A checked source listing and deterministic trace support the logic. A native authorized run would additionally test the editor behavior and runtime differences. Interview honesty means distinguishing what you ran from what you planned and calculated on paper.