Module 5 - Messages and User Inputs
Lesson 5.4 - The Excel Input Box
Topic 5.4.3 - Cancelling the Input Box

When you cancel a generic VBA input box it simply returns an empty string.  This works a little differently for an Excel input box:

Cancel input

We almost fell into the trap! But what happens when we click the Cancel button?

 

Files Needed

You don't need any files for this section.

Completed Code

Click here to download a workbook containing the sample code.

Create a new workbook and insert a module in the VBE.

Cancelling an Input Box

To demonstrate what happens when an Excel input box is cancelled, we'll return the result to a Variant variable.  Create a new subroutine called CancelInputBox and add code to return the result of an Excel input box to a Variant variable:

Return to variant

It doesn't matter what question you display on the input box as we're going to cancel it anyway.

 

We can step through the code above and then cancel the input box when it appears:

Cancel input box

It doesn't matter what you type in when you're going to cancel the input box.

 

Using the Locals window reveals the value that is returned by the input box:

Retrun value

The input box returns the Boolean value False when it is cancelled.

 

The Value Returned to Different Data Types

The default value that is returned when an Excel input box is cancelled is the Boolean value False.  The exact value that you'll end up with in the variable depends on the data type that you're using.  The table below shows a brief summary of these values:

Variable data type Value returned
Boolean False
String "False"
Any numeric data type 0
Date #00:00:00#

To practise cancelling an Excel input box:

  1. In the same module, create a subroutine called CancelMe.
  2. Add code to display an Excel input box and capture its result in a String variable.  Display the captured value in a message box:

Sub CancelMe()

 

Dim YourName As String

 

YourName = Application.InputBox("Enter your name")

 

MsgBox "Hello " & YourName

 

End Sub

  1. Run the subroutine and cancel the input box when it appears:
Cancel input box

It doesn't matter if you type anything into the input box, just click the Cancel button.

 
  1. Check that you see a message similar to the one shown below:
Message box

Not the most useful message!

 
  1. Add code to check if the return value of the input box is "False" and take an appropriate action if so:

Sub CancelMe()

 

Dim YourName As String

 

YourName = Application.InputBox("Enter your name")

 

If YourName = "False" Then

MsgBox "Subroutine cancelled", vbExclamation

Exit Sub

End If

 

MsgBox "Hello " & YourName

 

End Sub

  1. Run the subroutine again and check that you see a sensible message when you cancel the input box:
Final message

A slightly more sensible message.

 
  1. Save and close the workbook.
This page has 0 threads Add post