Yes. In VBA, use vbOKCancel as the buttons argument of MsgBox, then check whether the function returned vbOK or vbCancel. For example, MsgBox("Continue?", vbOKCancel, "Confirm") displays the two buttons; assigning its result to a variable lets your macro take a different action for each choice.
What OK and Cancel mean in a VBA MsgBox
MsgBox is a built-in VBA function that displays a dialog and returns a value after the user responds. Its first argument is the message text. The second argument is a button-and-icon setting, and the optional third argument supplies the dialog title. The button setting vbOKCancel displays an OK button and a Cancel button.
The important distinction is that the visible labels are not the values VBA gives your code. The function returns a value of type VbMsgBoxResult: vbOK when the user chooses OK, or vbCancel when the user chooses Cancel. Your code should compare the result with those named constants instead of treating the response as text.
OK and Cancel usually mean proceed with the requested action or stop it. They do not have any built-in effect on a workbook: the buttons only report the choice. Your macro must decide what to do with that result.
A basic OK/Cancel example
This complete Excel VBA procedure asks before making a change. It exits without changing anything if the user cancels. The sample change is deliberately simple; replace it with the action your own macro needs to perform.
Option Explicit
Sub AskBeforeChangingCell()
Dim answer As VbMsgBoxResult
answer = MsgBox("Replace the value in A1?", _
vbOKCancel + vbQuestion, _
"Confirm change")
If answer = vbCancel Then
Exit Sub
End If
If answer = vbOK Then
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = "Updated"
End If
End Sub
The underscore at the end of a line is VBA’s line-continuation character, so the three lines beginning with answer = MsgBox form one statement. vbQuestion adds a question-mark icon; it does not change the returned result. The test for Cancel makes the stop path explicit, while the OK test makes the action clear to a reader maintaining the macro.
Before running a macro that edits a workbook, save a copy of the file. VBA changes cannot be undone with Ctrl+Z, even when the change appears small. Save a macro-enabled workbook as an .xlsm file if it needs to retain its VBA code.
How the return value controls program flow
A message box pauses the running procedure while it waits for the user to respond. Once the user clicks a button, VBA resumes at the next line and makes the result available to the calling code. This makes an OK/Cancel box useful as a checkpoint before deleting records, overwriting a range, exporting a file, or carrying out another consequential step.
For a small procedure, an If statement is usually enough. If the choices lead to several substantial actions, Select Case can make the branching easier to read:
Option Explicit
Sub ChooseAction()
Dim answer As VbMsgBoxResult
answer = MsgBox("Save these changes?", vbOKCancel, "Save")
Select Case answer
Case vbOK
SaveChanges
Case vbCancel
Exit Sub
End Select
End Sub
In this example, SaveChanges stands for a procedure that exists elsewhere in the project. If you paste the sample into a module by itself, define that procedure or replace the call before running it. When a user cancels, Exit Sub ends the current procedure; it does not automatically reverse work already performed earlier in the macro. Put the confirmation before the action you want the user to be able to prevent.
Choosing buttons, icons, and the default
The second argument to MsgBox combines settings. Use vbOKCancel for the buttons and optionally add an icon or a default-button setting. The plus sign is commonly used to combine these VBA constants; Or is also suitable for combining the bit values.
vbOKOnlyshows only OK. It is the default button arrangement if you omit a button constant.vbOKCancelshows OK and Cancel.vbYesNoshows Yes and No, whilevbYesNoCanceladds Cancel. Choose labels that describe the decision rather than using OK and Cancel automatically.vbQuestion,vbInformation,vbExclamation, andvbCriticalselect different icons. The icon is visual context, not a substitute for clear message wording.vbDefaultButton1andvbDefaultButton2specify which displayed button is initially selected. For OK/Cancel, the second button is Cancel.
For example, vbOKCancel + vbQuestion + vbDefaultButton2 displays OK and Cancel with a question icon and makes Cancel the default selection. The default button matters because the user may press Enter rather than click. In a confirmation that could trigger a destructive operation, choosing a cautious default can reduce accidental acceptance. Keep the prompt specific enough that the user knows what OK will do.
OK/Cancel compared with Yes/No
Use OK and Cancel when the dialog confirms or interrupts an operation: for example, “Overwrite the existing report?” or “Continue with deleting these rows?” Use Yes and No when the user is answering a direct question and both answers are meaningful choices. A third Cancel button can be appropriate when the user may want to abandon the decision entirely.
These are design choices, not different kinds of VBA logic. vbYesNo returns vbYes or vbNo, whereas vbOKCancel returns vbOK or vbCancel. A common mistake is to show one set of labels but compare the result against constants for another set. Keep the button constant and the values in the later tests matched.
Common mistakes and practical fixes
- Showing the buttons but ignoring the result: Calling
MsgBoxwithout assigning its return value is fine for an informational message, but it cannot guide an OK/Cancel decision. Store the result in a variable or compare the function call directly in anIfstatement. - Comparing with the label as a string: The result is not the text “OK” or “Cancel.” Compare it with
vbOKandvbCancel, which are the appropriate named result constants. - Using the wrong constant: A comparison to
vbNowill not detect Cancel in an OK/Cancel box. Match each button set to its corresponding return values. - Putting the confirmation too late: A prompt after a file has been overwritten cannot prevent that overwrite. Ask before the action, and exit on Cancel before changing data.
- Assuming Cancel rolls back work: Cancel only tells your procedure which button was pressed. It does not undo earlier VBA statements or restore workbook data.
- Writing a vague prompt: “Are you sure?” does not identify the action. Say what will happen, such as “Delete the 12 selected rows?” so the choice has enough context.
When debugging, set a breakpoint on the line after the MsgBox call and inspect the variable in the Visual Basic Editor. Confirm that the code reaches the right branch when you click each button. In Excel for Microsoft 365 on Windows, open the editor with Alt+F11; on a Mac, use Option+F11, sometimes with Fn as well depending on the keyboard’s function-key settings, or use Developer > Visual Basic.
Where MsgBox is appropriate—and where it is not
A modal message box is useful for a short, immediate question during a manually run macro. Because the user must respond before the procedure continues, it is a poor fit for unattended automation, frequent repetitive prompts, or workflows where a user needs to review a large amount of information. A macro that displays many message boxes can become slow and frustrating, particularly when processing many rows.
For a larger decision, consider a custom VBA UserForm. A form can present more explanation, multiple fields, or clearer choices than a compact message box. For a routine that should run without interruption, use an explicit rule or a configurable setting instead of asking a person each time. Do not put interactive prompts into a worksheet function intended to calculate cell values; worksheet functions are expected to return results to cells, not interrupt calculation with dialogs.
Macros can run only when the workbook is opened in a desktop version of Excel with macro support and the relevant security settings allow them. Excel for the web does not run VBA macros. On Windows and Mac desktop Excel, the exact security prompts and available controls can differ, but the safe principle is the same: enable macros only for files from a source you trust. A confirmation box is not a security boundary and does not make an untrusted macro safe.
Frequently Asked Questions
What is the VBA code for an OK/Cancel MsgBox?
Use MsgBox("Your message", vbOKCancel, "Your title"). Assign the result to a variable if the macro needs to respond differently to OK and Cancel.
What does MsgBox return when I click Cancel?
With vbOKCancel, clicking Cancel returns vbCancel. Pressing Esc also acts as Cancel for this button arrangement.
How do I make Cancel the default button?
Add vbDefaultButton2 to the button settings, for example vbOKCancel + vbDefaultButton2. The second button in this arrangement is Cancel, so it is selected by default.
Can I use OK and Cancel in an Excel worksheet formula?
No. MsgBox is a VBA function for code running in the desktop application, not a worksheet formula. Put it in a VBA procedure, and do not use it as an interactive prompt inside a worksheet function.
Can I undo a macro after choosing OK?
Usually not with Excel’s Undo command. VBA changes cannot be undone with Ctrl+Z, so save a separate copy before running a macro that modifies workbook data.
Putting the choice to work
The core pattern is simple: display the message with vbOKCancel, capture the return value, and handle vbOK and vbCancel deliberately. Clear wording, a sensible default, and a confirmation placed before the consequential action make that small dialog far more useful. For complex or unattended workflows, choose a form or a rule-based alternative rather than relying on repeated prompts.
Related
- Data Validation Framework: Design, Rules, and Examples
- What Is Power Query? Excel Data Cleanup Explained
- AI and Power Query: What It Can and Cannot Do in Excel
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA UserForm Progress Bar: Build One That WorksTo add an Excel VBA UserForm progress bar, create a UserForm with a Frame and a colored Label…
- Excel VBA: Get the Last Day of a MonthIn Excel VBA, use DateSerial(Year(d), Month(d) + 1, 0) to get the final date of the month containing…
- VBA Copy and Paste a File: Practical Code and Safe StepsTo copy a file with VBA in Excel for Microsoft 365 on Windows, use the FileCopy statement or…
- Excel VBA Input Box With a Drop-Down ListExcel’s built-in VBA InputBox cannot display a drop-down list. To let someone choose from fixed options, create a…
- Excel VBA: Highlight the Active CellTo highlight the active cell in Excel for Microsoft 365 on Windows, put a Worksheet_SelectionChange event in that…
- VBA Move UserForm Without a Mouse: Keyboard MethodsYes. In Excel VBA, move a UserForm in code by changing its Left and Top properties; to move…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.