Search
Close this search box.

VBA Input Box


The InputBox function asks users to enter values. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox method returns the text in the textbox. If the user selects the Cancel button, the function returns an empty string (“”).

Syntax:

InputBox(Prompt[, Title[, Default[, Helpfile[, ContextID]]]])

Parameters:

  • Prompt: The text to display in the input box.
  • Title: The title of the input box.
  • Default: The default value to be displayed in the input box.
  • Helpfile: The path to a help file.
  • ContextID: The context ID within the help file.

Example:

  1. The InputBox function displays a dialog box with the prompt “Please enter your name:” and the title “User Input.”
  2. The user enters their name.
  3. The entered name is stored in the userName variable.
  4. A message box is displayed, greeting the user with their name.
				
					Sub GetUserName()
    Dim userName As String

    userName = InputBox("Please enter your name:", "User Input")

    MsgBox "Hello, " & userName & "!"
End Sub
				
			

Additional Tips:

  • You can use the Type argument to specify the data type of the input (e.g., vbString, vbInteger).
  • For more complex input, consider using a UserForm, which provides a more flexible and customizable interface.
  • To validate user input, you can use conditional statements and error handling techniques.

Example with Data Validation:

				
					Sub GetValidNumber()
    Dim number As Integer

    Do
        number = InputBox("Enter a number between 1 and 10:", "Number Input")
    Loop Until IsNumeric(number) And number >= 1 And number <= 10

    MsgBox "You entered: " & number
End Sub
				
			

This example ensures that the user enters a valid number between 1 and 10. It uses a Do...Loop loop to repeatedly prompt the user until a valid input is provided.

By effectively using the InputBox function, you can create interactive and dynamic VBA applications that engage with the user.