How to use InputBox function in VBA?

In VBA (Visual Basic for Applications), the `InputBox` function is used to display a prompt in a dialogue box, wait for the user to input text or click a button, and return the content of the text box. The `InputBox` function can be particularly useful for getting a single piece of information, such as a user’s name or a specific number.

Here is the basic syntax for the `InputBox` function:

InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])

Where the parameters are:

  • `prompt` (required): The message to be displayed as a prompt in the dialogue box.
  • `title` (optional): The title for the dialogue box. If omitted, the application name is used.
  • `default` (optional): The default value that appears in the text box when the input box is displayed.
  • `xpos` and `ypos` (optional): Numeric expressions that specify the position of the dialogue box on the screen. If omitted, the box is centered.
  • `helpfile` and `context` (optional): Arguments that provide context-sensitive help. Omit these unless you have set up a help file.

Here’s an example of how to use the `InputBox` function:

Sub GetUserInput()
    ' Declare a variable to store the user input
    Dim userName As String
    
    ' Prompt the user for their name
    userName = InputBox("Please enter your name:", "User Name")
    
    ' Check if user has entered something or clicked Cancel
    If userName <> "" Then
        ' Do something with the input
        MsgBox "Hello, " & userName & "!"
    Else
        ' Handle the case where no input was provided
        MsgBox "Name entry was cancelled or left blank."
    End If
End Sub

When running this code, an input box will appear, asking the user to enter their name, with a title “User Name” on the dialogue box. If the user enters a name and clicks OK, a greeting message box will appear. If the user clicks Cancel or closes the input box, a different message will be shown.

Here are some points to remember when using the `InputBox` function:

  • If the user clicks “Cancel”, the `InputBox` function returns an empty string (“”).
  • Use the `StrPtr` function if you need to distinguish between an empty string returned because the user hit “Cancel” and an empty string returned because the user hit “OK” without entering anything (`StrPtr` will return 0 in the case of “Cancel”).
  • In more advanced scenarios, you’ll want to perform data validation to ensure the input is of the correct type and format before using it in your code.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project