Analyst Cave

VBA InputBox – How to request user input?

The VBA InputBox is a very useful VBA user input feature along the VBA Message Box, before needing to reach out for VBA UserForms The InputBox allows you to create a simple pop-up message with a single user input textbox.

A disclaimer to begin with: Refrain from using the InputBox for yes/no, binary questions, as shown above. Use the VBA Message Box instead – configure the buttons to vbYesNo.

InputBox function definition

Let us start with the InputBox function definition:

InputBox( Prompt, [Title], [Default], [XPos], [YPos], [HelpFile], [Context])

As noticed above the InputBox function requires, as a minimum, only the Prompt parameter to execute. What do the parameters stand for?

The VBA InputBox is a modal dialog box. This means it must be closed or hidden before you can continue working in VBA, Excel, PowerPoint or any other application.

The VBA InputBox return the value input by the user in the input textbox.

InputBox examples

Time to explore some code examples

InputBox "How old are you"?


Now let’s add a Title and a Default value.

InputBox "Shall we continue? (yes/no)", "Continue or end", "yes"


Notice that if you want to request specific input from the user you need to suggest (e.g. in brackets) the available options.

Get value provided by user

The function is modal hence prevents further execution until the user provides the required value. Getting the provided value is easy as it is returned by the InputBox function:

Dim val As Long
val = InputBox("How old are you?")

Resolving errors / incorrect input

The VBA InputBox does not prevent the user from providing random / junk values so you need to handle validation yourself. I suggest a simple InputBox validation loop as such:

Dim val As String

Do Until IsNumeric(val)
  val = InputBox("How old are you?")
Loop
'Success
Debug.Print "You are " & val " years old"

Summary

Use the VBA InputBox function instead of custom VBA UserForms whenever possible. Why reinvent the wheel? Similarly you can stretch/customize the VBA Message Box.

Exit mobile version