Función InputBox de VBA - ¿Cómo crear InputBox y almacenar valores?

Tabla de contenido

InputBox de Excel VBA

VBA InputBox es una función incorporada que se utiliza para obtener un valor del usuario, esta función tiene dos argumentos principales en los que uno es el encabezado del cuadro de entrada y otro es la pregunta del cuadro de entrada, la función del cuadro de entrada puede almacenar solo los tipos de datos de entrada que puede contener la variable.

A menudo, en Excel, utilizamos los datos que ya están en la hoja de Excel. A veces también necesitamos algún tipo de datos de entrada de los usuarios. Especialmente en VBA, a menudo se requiere la entrada del usuario.

Usando InputBox, podemos obtener los datos del usuario y usarlos para nuestro propósito. Un InputBox le pedirá al usuario que ingrese el valor mostrando el InputBox.

Sintaxis

  • Aviso: no es más que el mensaje al usuario a través de un cuadro de entrada.
  • Título: ¿Cuál es el título del cuadro de entrada?
  • Predeterminado: ¿Cuál es el valor predeterminado del cuadro de entrada? Este valor aparece en el área de escritura del cuadro de entrada.

Estos tres parámetros son suficientemente buenos en Excel. Ignore los otros 4 parámetros opcionales. Para comprender esta sintaxis, mire la siguiente captura de pantalla.

¿Cómo crear InputBox en VBA?

Ok, vayamos directamente a la practicidad. Siga los pasos a continuación para crear su primer cuadro de entrada.

Paso 1: Vaya a VBE (Editor de Visual Basic) e inserte un nuevo módulo.

Paso 2: haga doble clic en el módulo insertado y cree un nombre de macro.

Paso 3: Comience a escribir la palabra "InputBox" y verá opciones relacionadas.

Paso 4: Seleccione el cuadro de entrada y dé espacio, y verá la sintaxis del cuadro de entrada.

Paso 5: Indique el mensaje "Ingrese su nombre".

Paso 6: escriba el título del cuadro de entrada como "Información personal".

Paso 7: escriba el valor predeterminado como "Escriba aquí".

Paso 8: hemos terminado. Ejecute este código y vea su primer cuadro de entrada.

Almacene el valor de InputBox en celdas

Ahora pasaremos por el proceso de almacenar valores en celdas. Siga los pasos siguientes.

Paso 1: declarar la variable como variante.

Código:

Sub InputBox_Example () Dim i como variante End Sub

Step 2: For this variable, assign the value through the inputbox.

Code:

Sub InputBox_Example() Dim i As Variant i = InputBox("Please Enter Your Name", "Personal Information", "Type Here") End Sub

Note: Once the input box comes to the right of the equal sign, we need to enter the arguments or syntax in brackets like our regular formulas.

Step 3: Now, whatever the value typed in the input box, we need to store it in cell A1. So for this, write the code as Range (“A1”).Value = i

Code:

Sub InputBox_Example() Dim i As Variant i = InputBox("Please Enter Your Name", "Personal Information", "Type Here") Range("A1").Value = i End Sub

Ok, we are done. Let’s run this code now by pressing the F5 key, or you can also run the code manually, as shown in the below screenshot.

As soon as you run this code, we will see the inputbox.

Type the name and click on Ok.

As soon as you type the name and click on OK, you will see the inputbox value in cell A1.

Note: We can store any value from the inputbox if the variable is defined properly. In the above example, I have defined the variable as a Variant, which can hold all types of data.

For example, now I have changed the variable type to Date.

Now run the code and type other than the date.

Click on ok and see what the response is.

We got the error value as Type mismatch. Since we have declared the variable data type as DATE, we cannot store anything other than DATE with an inputbox.

Now enter the date and see what happens.

As soon as you type the date and then click on OK and see what the response is.

Since we have entered the correct value, we got the result in the cell.

Validation of Input from User

You know what we can actually allow users to enter only specific value i.e., allow the user to enter only text, only number, only logical values, etc.

To perform this task, we need to use the method Application.InputBox.

Let’s look at the syntax of the Application.InputBox.

  • Prompt: This is nothing but the message to the user through an input box.
  • Title: What is the title of the input box?
  • Default: What is the default value of the input box? This value appears in the typing area of the input box.
  • Left: What should be the x position of the input box in the current window?
  • Top: What should be the y position of the inputbox in the current window?

To start this, inputbox declare variable and assign the value to a variable.

Now to assign value to start the word Application.

After the word Application, put a dot (.) and type Inputbox.

Select the input box and open the bracket.

As usual, enter Prompt, Title, and Default Value.

Now ignore left, top, help file, help context ID by typing 5 commas (,).

Here Type means what should be the input string. Below are the validations available.

Entonces, en consecuencia, seleccione su tipo. He seleccionado 1 como parámetro, es decir, solo números.

Ahora ejecute el código y el tipo de valor de texto.

Haga clic en Aceptar y vea qué sucede.

Dice que el número no es válido. Entonces, podemos ingresar solo números en este cuadro de entrada.

Cosas para recordar

  • Necesitamos una variable para almacenar el valor dado por el cuadro de entrada.
  • Si está utilizando InputBox sin el método Application, debería ser perfecto sobre el tipo de datos variables.
  • Utilice el tipo de datos Variant, que puede contener cualquier tipo y almacenamiento de datos.

Articulos interesantes...