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:
Example:
InputBox
function displays a dialog box with the prompt “Please enter your name:” and the title “User Input.”userName
variable.
Sub GetUserName()
Dim userName As String
userName = InputBox("Please enter your name:", "User Input")
MsgBox "Hello, " & userName & "!"
End Sub
Additional Tips:
Type
argument to specify the data type of the input (e.g., vbString
, vbInteger
).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.