Excel VBA interview questions, from ranges to robust macros
VBA interview questions test whether you can automate Excel without making the workbook fragile: working with Range, Cells and worksheet objects without Select, reading data into arrays, declaring types under Option Explicit, and handling errors so a failed macro leaves Excel in a usable state. Expect questions on events, Dictionary and Collection, speed settings, and a short practical task such as cleaning or consolidating sheets. Senior rounds ask when a macro should become Power Query, Python or a proper application instead.
By Evin JohnPublished 11 min read
Who still hires for VBA, and how the interview runs
VBA lives where spreadsheets carry real work: finance and accounting close processes, banking operations, insurance and actuarial models, supply chain planning and management reporting. The job titles vary (reporting analyst, MIS executive, Excel and VBA developer, operations analyst, FP&A analyst), but the hiring worry is the same. Teams have macros that someone wrote years ago, they break when a file layout changes, and nobody wants to touch them. Interviewers look for a person who writes code that the next analyst can read, and who knows the limits of the tool.
- Screening questionsBasic syntax and the Excel object model, often by phone or in a short call with the hiring manager.
- Code readingA macro on screen with Select, ActiveSheet and hard-coded rows. You explain what it does and what breaks first.
- Practical testA workbook and a task: clean a data dump, split it into sheets, build a summary, or merge files from a folder. Often 30 to 90 minutes.
- Process conversationHow you test, document and hand over macros, protect sensitive data, and decide what not to automate.
Fundamentals: syntax, types and the object model
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is the difference between a Sub and a Function? | Basics | A Function returns a value and can be used as a worksheet formula (a UDF) if it is public in a standard module; a Sub performs actions and is what you assign to a button |
| Why put Option Explicit at the top of every module? | Habits | It forces declarations, so a typo in a variable name becomes a compile error instead of a new empty Variant that silently holds nothing |
| Integer or Long for a row counter? | Types | Long. Integer tops out at 32,767, which a large sheet passes easily, giving an overflow error; modern VBA handles Long just as fast |
| What is a Variant, and when is it the right type? | Types | A type that can hold anything, including Empty, Null and arrays. Right for a range read into an array or a value of unknown type; wasteful and error-hiding for ordinary counters |
| How are arguments passed by default? | Procedures | ByRef, so a procedure can change the caller's variable. Use ByVal when it should not, and say so explicitly in shared code |
| ThisWorkbook versus ActiveWorkbook? | Object model | ThisWorkbook is the file holding the code; ActiveWorkbook is whatever the user has in front. Code that means its own file should never rely on what happens to be active |
| Why do experienced developers avoid Select and Activate? | Object model | They are slow, they depend on screen state and they fail on hidden sheets. Work through fully qualified references such as ws.Range("A1") instead |
| Range("A1") versus Cells(1, 1)? | Ranges | Same cell. Cells takes numbers, which suits loops; Range takes an address string, which suits fixed blocks. Both should be qualified with a sheet |
| What does a With block do? | Readability | Lets you refer to one object several times without repeating it, which shortens code and avoids repeated lookups |
| What is the difference between Value, Value2 and Text? | Ranges | Value converts dates and currency to VBA types; Value2 returns the raw number; Text returns what is displayed, so it can show #### when the column is narrow |
Ranges, the last row and arrays
Almost every practical test needs the last used row. The common answer is ws.Cells(ws.Rows.Count, "A").End(xlUp).Row, which works from the bottom of a column up to the last value. Good candidates add the caveat: it looks at one column, so pick a column that is always filled, and do not trust UsedRange, which can remember cells that once had formatting. The bigger idea interviewers want to hear is to touch the sheet as rarely as possible. Reading 20,000 cells one by one is slow; reading them into a Variant array is one call.
Option Explicit
Sub FlagLateInvoices()
Dim ws As Worksheet
Dim lastRow As Long, i As Long
Dim data As Variant, result() As Variant
Set ws = ThisWorkbook.Worksheets("Invoices")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
If lastRow < 2 Then Exit Sub ' header only, nothing to do
' A = invoice id, B = due date, C = paid date (blank if unpaid)
data = ws.Range("A2:C" & lastRow).Value ' 2-D array, 1-based
ReDim result(1 To UBound(data, 1), 1 To 1)
For i = 1 To UBound(data, 1)
If IsEmpty(data(i, 3)) Then
If data(i, 2) < Date Then result(i, 1) = "Overdue" Else result(i, 1) = "Open"
ElseIf data(i, 3) > data(i, 2) Then
result(i, 1) = "Paid late"
Else
result(i, 1) = "Paid on time"
End If
Next i
ws.Range("D2").Resize(UBound(result, 1), 1).Value = result
End SubTwo follow-ups often come next. First, a range of one cell returns a single value, not an array, so code that may meet a one-cell range has to check. Second, VBA's And does not short-circuit: If Not obj Is Nothing And obj.Value > 0 still evaluates the right side and fails. That is why the snippet nests the checks instead of joining them with And.
- How do you delete rows that meet a condition? Loop from the bottom up, because deleting while moving down skips the row that slides into place. Faster still: filter and delete visible rows, or collect rows with Union and delete once.
- How do you find a value without looping? Range.Find, or Application.Match on an array. Mention that Find remembers settings such as LookAt from the last search, so set them every time.
- WorksheetFunction.Match versus Application.Match? The first raises a run-time error when nothing is found; the second returns an error value you can test with IsError, which is often easier to handle.
- How do you resize an array and keep its contents? ReDim Preserve, which can only change the last dimension. Growing it inside a loop is slow, so size it once when you can.
- What is the difference between a static and a dynamic array? A static array has fixed bounds at declaration; a dynamic one is declared empty and sized later with ReDim.
Error handling that leaves Excel in a good state
A favorite trap question: "What does On Error Resume Next do, and why is it dangerous?" It skips every error that follows, so a broken macro reports success and leaves wrong numbers behind. Use it for one line where an error is expected, check Err.Number right after, and switch handling back on with On Error GoTo 0. For whole procedures, interviewers want a single exit path that restores whatever the macro changed.
Sub RunMonthlyReport()
Dim calcMode As XlCalculation
calcMode = Application.Calculation
On Error GoTo CleanFail
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
BuildSummary ' your own procedures
ExportSummaryPdf
CleanExit:
Application.Calculation = calcMode
Application.EnableEvents = True
Application.ScreenUpdating = True
Exit Sub
CleanFail:
MsgBox "Report stopped: " & Err.Description & " (error " & Err.Number & ")", vbExclamation
Resume CleanExit
End Sub| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does Resume do, compared with Resume Next and Resume a label? | Error flow | Resume retries the failing line, Resume Next continues after it, Resume label jumps to cleanup; all three clear the active error |
| How do you raise your own error? | Validation | Err.Raise with a number offset from vbObjectError and a clear description, so callers can tell your errors from Excel's |
| How do you debug a macro that fails only on a colleague's machine? | Debugging | Check references, regional date and decimal settings, file paths, the Excel version and whether the file is open from a synced folder; add logging rather than guessing |
| What tools does the VBA editor give you? | Debugging | Breakpoints, stepping with F8, the Immediate window with Debug.Print, the Locals and Watch windows, and Debug.Assert |
Events, forms and class modules
Event questions usually start with Worksheet_Change. The trap is a handler that writes to the sheet, which fires the event again. Turning events off while the handler writes, and back on at the end even after an error, is the answer interviewers want, along with Intersect to limit the handler to the cells that matter.
' In the worksheet's own code module
Private Sub Worksheet_Change(ByVal Target As Range)
Dim changed As Range, cell As Range
Set changed = Intersect(Target, Me.Range("B2:B500"))
If changed Is Nothing Then Exit Sub
On Error GoTo SafeExit
Application.EnableEvents = False
For Each cell In changed.Cells
cell.Offset(0, 1).Value = Now ' timestamp in column C
Next cell
SafeExit:
Application.EnableEvents = True
End Sub- Which workbook events have you used? Workbook_Open for setup, BeforeSave for checks, BeforeClose for cleanup. Say that Open does not run when macros are disabled, so nothing important should depend on it alone.
- How would you validate a UserForm before saving its data? Check each control in the OK button's handler, show one clear message, set focus on the first bad field, and only then write to the sheet.
- What is a class module for? Your own objects with properties and methods, and handling events from other objects (for example a class that holds a WithEvents reference to an application or chart).
- What is the difference between a Collection and a Dictionary? Collection is built into VBA and is fine for an ordered list. Dictionary, from the Scripting runtime, has Exists, Keys, Items and settable compare modes, so it suits lookups and de-duplication. It is not available in Excel for Mac.
- Early binding or late binding? Early binding (a reference plus a declared type) gives IntelliSense and constants; late binding (CreateObject and As Object) avoids broken references when users have different library versions.
Function TotalsByRegion(src As Range) As Object
' src: two columns (region, amount), two or more rows, no header
Dim totals As Object, data As Variant, i As Long, key As String
Set totals = CreateObject("Scripting.Dictionary")
totals.CompareMode = vbTextCompare ' "north" and "North" are one key
data = src.Value
For i = 1 To UBound(data, 1)
key = Trim$(CStr(data(i, 1)))
If Len(key) > 0 Then totals(key) = totals(key) + data(i, 2)
Next i
Set TotalsByRegion = totals
End Function
Sub PrintRegionTotals()
Dim t As Object, k As Variant
Set t = TotalsByRegion(ThisWorkbook.Worksheets("Sales").Range("A2:B200"))
For Each k In t.Keys
Debug.Print k, t(k)
Next k
End SubExpect the question "Why does totals(key) + amount work for a key that is not there yet?" Reading a missing key from a Dictionary adds it with an Empty value, and Empty plus a number is that number. It is convenient, but the same behavior means a typo in a lookup quietly creates keys, so use Exists when you only want to read.
Senior and scenario questions
- A macro that ran in two minutes now takes forty. What do you check? Cell-by-cell loops, Select calls, recalculation and screen updating left on, volatile formulas recalculating on every write, and whether the data simply grew past what the design can handle.
- How do you merge every workbook in a folder into one sheet? Loop the files with Dir or FileSystemObject, open each read-only, copy values (not formats) under the last row, close without saving, and log any file that failed instead of stopping.
- How would you send a report by email from Excel? Automate Outlook with late binding, build the message and attach the PDF, and show it for review rather than sending it unseen; mention that security prompts and company policy may block automated sending.
- How do you pull data from a database into Excel with VBA? ADO with a connection string, a parameterized command rather than glued-together SQL, and CopyFromRecordset to write the result in one step.
- How do you keep VBA code under version control? Export modules, forms and classes as text files and commit those, since the binary workbook shows no useful diff.
- How do you make macros safe to share? Signed projects, files kept in trusted locations, no passwords stored in code, and clear notes on what each macro changes.
- Does your code need to run on Mac? Then avoid Windows-only pieces such as the Scripting runtime and ActiveX controls, and build paths with Application.PathSeparator instead of a typed backslash.
- When would you replace a macro? When the job is really data shaping, Power Query is easier to maintain. When it is heavy analysis, Python or a database fits better. For Excel on the web, Office Scripts is the newer route. Keep VBA where it is stable, tested and close to the user.
Fictional example
- At an equipment rental firm, month-end depended on a macro that copied twelve branch files into one summary. It broke whenever a branch added a column, and when it broke it left calculation on manual, so people saw stale totals without knowing. I rewrote it in three steps. I matched columns by header name instead of position, so a new column no longer shifted the data. I read each file into an array and wrote it once, which cut the run from about eight minutes to under one. I added one cleanup path that always restored Excel's settings and wrote a log sheet listing each file and its row count. The finance lead now checks the log, not my inbox, and the next two layout changes needed no code change at all.
A ten-day VBA practice plan
- Days 1 and 2: types, Option Explicit, Sub and Function, ByRef and ByVal. Write three small UDFs and use them in cells.
- Days 3 and 4: ranges without Select. Find the last row, copy filtered rows to a new sheet, and do the same with an array to feel the speed difference.
- Days 5 and 6: error handling with one cleanup path, then a Worksheet_Change handler that logs edits without looping on itself.
- Days 7 and 8: Dictionary and Collection, a folder merge, and exporting a summary to PDF.
- Days 9 and 10: take an old recorded macro, rewrite it cleanly, and explain the changes out loud in five minutes as if to a hiring manager.
VBA questions often come in the same loop as spreadsheet skills, so read the Excel interview questions for lookups and pivots. Reporting jobs that are moving to BI tools may add Power BI or Looker, and data pulls lead to SQL.
For a VBA round, the useful practice is talking through a macro while you write it. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of a mock session so you can see where your explanation drifted. In practice it can read a macro or a task sheet from a screenshot and suggest an approach, and with Pro or the free trial it can draw on your résumé and the job description when it drafts answers about your past automation work.
Questions people ask
What are common VBA interview questions?
Sub versus Function, why Option Explicit matters, Long versus Integer, ByRef and ByVal, how to find the last row, why to avoid Select, how On Error GoTo works, how to stop Worksheet_Change from firing itself, and when to use a Dictionary.
What is in a VBA practical test?
Usually a workbook and a task such as cleaning a data dump, splitting rows into sheets, building a summary or merging files from a folder. Interviewers watch for qualified references, arrays instead of cell-by-cell loops, and error handling that restores Excel's settings.
How do I make a slow VBA macro faster?
Read and write ranges as arrays, remove Select and Activate, turn off screen updating, events and automatic calculation while it runs and restore them at the end, and use Find, Match or a Dictionary instead of nested loops.
Is VBA still worth learning for interviews?
For finance, operations and reporting roles that run on Excel, yes, because many teams maintain existing macros. It also helps to know when Power Query, Python or Office Scripts would be the better tool.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
