How to use Application.InputBox in the xlwings API way

The Application.InputBox method in Excel VBA is a versatile tool for displaying a dialog box that prompts the user for input. In xlwings, this functionality is exposed through the api property, allowing direct access to the underlying Excel object model. This method is particularly useful for creating interactive Excel applications where you need to gather specific information from the user, such as a string, number, cell reference, or even a formula. Unlike a simple input box, it can validate the type of input, making data collection more robust.

Syntax in xlwings:
The method is accessed via the Application object. The general xlwings API call format is:

app.api.InputBox(Prompt, Title, Default, Left, Top, HelpFile, HelpContextID, Type)

Where:

  • Prompt (Required, String): The message displayed in the dialog box.
  • Title (Optional, Variant): The title for the input box window. If omitted, the default title is “Input”.
  • Default (Optional, Variant): A default value that appears in the text box when the dialog is shown.
  • Left, Top (Optional, Variant): The screen coordinates (in points) for the upper-left corner of the dialog box.
  • HelpFile, HelpContextID (Optional, Variant): Identifiers for a custom Help file.
  • Type (Optional, Variant): Specifies the return data type. If omitted, it defaults to 0 (a String). This is a critical parameter.

The Type argument can take the following values:

ValueMeaning
0A formula
1A number
2Text (a string)
4A logical value (True or False)
8A cell reference, as a Range object
16An error value, such as #N/A
64An array of values

You can sum these values to allow multiple types (e.g., Type=1+2 allows both numbers and text). If the user enters data of an incorrect type or clicks “Cancel”, the method returns False.

Code Examples:

  1. Prompting for a Text String (Default):
import xlwings as xw
app = xw.apps.active
user_name = app.api.InputBox(Prompt="Enter your name:", Title="User Info", Type=2)
if user_name is not False:
    print(f"Hello, {user_name}")
  1. Prompting for a Number with a Default Value:
budget = app.api.InputBox("Enter the project budget:", "Budget Input", Default=10000, Type=1)
if budget is not False:
    total = budget * 1.1
    print(f"Budget with contingency: {total}")
  1. Prompting for a Cell Reference (returns an xlwings Range object):
target_range = app.api.InputBox("Select a data range:", "Range Selector", Type=8)
if target_range is not False:
    # target_range is an xlwings Range object
    values = target_range.value
    print(f"Selected values: {values}")
  1. Allowing Multiple Input Types (Number or Text):
data = app.api.InputBox("Enter ID (number) or Name (text):", "Data Entry", Type=1+2)
if data is not False:
    print(f"Received: {data} (Type: {type(data).__name__})")

April 12, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *