In Access VBA, use InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context]) to show a simple dialog and receive the user’s response as a string. The prompt is required; the other arguments let you set the caption, initial text, position, and optional Help topic.
Access VBA InputBox syntax
InputBox is a built-in VBA function, so you can call it from an Access form, report, standard module, or other VBA procedure without adding a reference. The brackets in the syntax below indicate optional arguments; they are explanatory notation and should not be typed literally.
' Syntax: InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])
Dim response As String
response = InputBox("Enter a value:", "Access prompt", "")
The function displays a modal dialog: VBA pauses at the call until the user clicks OK or Cancel. The returned value is text, even when the person types digits. InputBox does not save a value to a table, update a control, or run a query by itself. Your code must decide what the response means and what action to take with it.
What each argument does
The arguments are positional, so their order matters. If you omit an argument in the middle but want to supply a later one, you generally need to include a placeholder for the omitted position.
promptis required. It is the message shown in the dialog. Write a clear instruction, such as “Enter the invoice number to find.”titleis optional and supplies the dialog’s title-bar text. If you omit it, VBA uses the application name.defaultis optional text placed in the input field initially. The user can accept it, replace it, or delete it.xposandyposare optional horizontal and vertical positions for the dialog. They are measured in twips. If omitted, VBA chooses a default location.helpfileandcontextare optional Help-system arguments. When you provide a Help file, you also provide its numeric context ID so the dialog can open the relevant topic.
For ordinary Access prompts, the first two or three arguments are usually enough. Positioning and Help arguments are less common in modern database interfaces, where a form can provide clearer instructions and a more consistent layout.
A basic Access example
This procedure asks for a customer name and displays the response. It deliberately treats a blank response as “no usable text,” but that condition also includes Cancel; the distinction matters and is covered below.
Public Sub AskForCustomerName()
Dim customerName As String
' Ask for a name; the final argument is the initial field value.
customerName = InputBox("Enter a customer name:", _
"Find a customer", "")
If Len(Trim$(customerName)) = 0 Then
MsgBox "No name was entered, or the prompt was canceled.", vbInformation
Exit Sub
End If
MsgBox "You entered: " & customerName, vbInformation
End Sub
Save a copy of the Access database before running a macro that changes data. VBA actions cannot be reversed with Ctrl+Z, so a backup is useful even when a small example appears harmless. This example only displays messages; it does not modify a table.
InputBox returns text, not a typed value
A common misconception is that entering a number makes InputBox return a numeric value. It returns a string in all cases. That is useful for preserving exactly what someone typed, but code must validate and convert the string before using it as a number, date, or other data type.
For instance, “12” may be converted to an integer, but “twelve” cannot. Blank text should also be considered before conversion. The following example accepts an integer quantity from 1 through 500 and handles invalid or out-of-range input. It treats Cancel and a blank answer the same way because InputBox does not expose a separate Cancel result.
Public Sub AskForQuantity()
Dim response As String
Dim quantity As Long
' Request a whole-number quantity.
response = InputBox("Enter a quantity from 1 to 500:", _
"Quantity", "1")
If Len(Trim$(response)) = 0 Then
MsgBox "No quantity was supplied.", vbInformation
Exit Sub
End If
If Not IsNumeric(response) Then
MsgBox "Enter a numeric quantity.", vbExclamation
Exit Sub
End If
On Error GoTo InvalidQuantity
quantity = CLng(response)
On Error GoTo 0
If quantity < 1 Or quantity > 500 Then
MsgBox "The quantity must be between 1 and 500.", vbExclamation
Exit Sub
End If
MsgBox "Accepted quantity: " & CStr(quantity), vbInformation
Exit Sub
InvalidQuantity:
MsgBox "That value cannot be converted to a whole number.", vbExclamation
End Sub
IsNumeric is a useful first check, but it does not guarantee that a value is a valid integer or within the range of the target variable. The conversion to Long can still fail for an excessively large value or a value unsuitable for that conversion, which is why the example includes an error handler and a separate range check. For dates, currency, or identifiers, choose a conversion and validation rule that matches the field’s actual data type and business rules.
Cancel, blank input, and default values
With the standard VBA InputBox function, clicking Cancel returns a zero-length string (""). Clicking OK after deleting all text also returns a zero-length string. Consequently, code cannot reliably tell whether the user canceled or deliberately submitted an empty answer by checking the return value alone.
A nonempty default can make this ambiguity more consequential: clicking OK without changing the field returns that default, while Cancel returns an empty string. If the distinction between Cancel and an intentionally blank answer is important, use a custom Access form with separate OK and Cancel buttons. The form can record an explicit choice and can also enforce required fields before accepting the response.
Do not use a default value as a substitute for validation. Users can edit or remove it. Check the final returned text before using it in a query, storing it, or converting it. For a search prompt, decide whether leading and trailing spaces should be trimmed; for a code or account number, those characters might be meaningful in some systems.
Where to call it in Access
You can call InputBox directly inside an event procedure, such as a form button’s Click event, or place it in a reusable procedure in a standard module. In the Access interface, open the form in Design View, select the button, open the Property Sheet, choose the Event tab, and use the builder beside the On Click property to create or open its event procedure. The VBA call itself is the same in either location.
For example, a short prompt may be suitable when a user occasionally needs to enter a search term. If the response will be used to filter records, your code still needs to apply it safely and decide how to handle quotes, wildcards, empty results, and invalid criteria. A prompt is only the input step; it does not automatically construct a safe or correct Access query.
When a value is required for a routine workflow, a bound or unbound form control is usually a better fit. A control stays visible, can have a label and validation rules, and can be combined with other fields. InputBox is most appropriate for a brief, one-off question where a separate form would add unnecessary friction.
InputBox compared with other options
Access VBA’s InputBox is not the same as Excel’s Application.InputBox. The standard VBA function returns text and has no argument for restricting the response to a particular Excel-style type. Excel’s Application.InputBox belongs to Excel’s object model and should not be assumed to be available as an Access feature.
In Access, choose the input method based on how much structure the user needs:
- Use
InputBoxfor a quick, single text response with minimal interface setup. - Use a form control when the user needs a visible label, a list of choices, required-field feedback, or multiple related values.
- Use a custom dialog form when you must distinguish Cancel from an accepted blank value or need more control over validation and layout.
- Use a parameter query when the value belongs in a query workflow and you want Access to request criteria as the query runs. A form-based parameter source can provide a more guided experience.
These approaches are not interchangeable in every database. A free-text prompt is convenient, but it gives users less guidance than a combo box, date control, or form with validation. The more important the value is to data quality, the more reason there is to use a structured interface.
Common problems and practical safeguards
Many InputBox problems come from treating the returned text as if it were already validated. Before using it, check for blank input, trim spaces if appropriate, validate its format, and convert it to the required data type. If the value will be used to select or modify records, verify that the resulting operation targets the intended records.
- Unexpected blank result: the user may have clicked Cancel or submitted an empty field. The standard function does not distinguish these actions.
- Type mismatch or conversion error: validate the text and handle conversion failures rather than assuming every response is usable.
- Prompt is difficult to understand: state what value is expected and give an example or allowed range in the prompt.
- Dialog position is awkward: omit
xposandyposunless custom placement is necessary; display scaling and window arrangements can make fixed positioning inconvenient. - Sensitive information is requested: InputBox displays typed characters normally. Do not use it to collect passwords or other secrets.
For database changes, avoid building SQL by simply joining untrusted prompt text into a command. Quotes and other characters can break the statement or alter its meaning. Prefer parameterized queries or properly managed DAO parameters where applicable, and test any data-changing procedure on a copy of the database first.
Frequently Asked Questions
What is the simplest InputBox syntax in Access VBA?
Use InputBox("Your prompt"). The prompt is required; title, default text, position, and Help information are optional.
How do I give an Access InputBox a title and default value?
Pass them as the second and third arguments, in that order: InputBox("Enter a code:", "Code lookup", "A100"). The default appears in the input field when the dialog opens.
How can I tell whether the user clicked Cancel?
You cannot distinguish Cancel from clicking OK with an empty field using the standard VBA InputBox function; both return a zero-length string. Use a custom form if the difference matters.
Does Access InputBox return a number?
No. It returns a string, including when the user types digits. Validate the response and convert it with an appropriate VBA conversion function before numeric calculations.
Can InputBox be used to enter a password?
It is not a password-masked control: typed characters are visible. Use a suitable form interface with a password-style text box and appropriate security practices instead.
Related
- Excel Data Validation Date Picker: Setup and Options
- Excel Data Validation for Dates: Rules and Examples
- Data Validation Checks in Excel: Rules and Examples
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Add Comments in Excel VBA: Notes and Threaded CommentsTo add a cell note with Excel VBA, select the cell and run ActiveCell.AddComment "Check this value." in…
- VBA Copy Paste Mode: How to Clear and Control ItIn Excel VBA, copy/paste mode is Excel’s temporary state after a cell or range has been copied or…
- Excel VBA Remove Duplicates: Methods and Safe CodeTo remove duplicate rows with Excel VBA, call the range’s RemoveDuplicates method and specify which columns define a…
- Excel VBA: Find the First Row Above a Value ThresholdTo find the first row where a cell’s value is greater than a threshold, loop through the relevant…
- VBA Code to Delete a Row in ExcelTo delete a worksheet row with VBA, use Rows(5).Delete for row 5. In a macro, qualify the row…
- Excel VBA Global Variables: Scope and ExamplesIn Excel VBA, a global variable is a value that procedures throughout the same VBA project can access.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.