Elementos Básicos de Visual Basic: Tutorial Práctico con Ejemplos de InputBox, MsgBox, IF y Select Case en Excel
Elementos Básicos de Visual Basic
Instrucciones básicas
variable = InputBox(mensaje [, título] [, predeterminado])
Ejemplo: las sentencias:
Dim edad As Integer
edad = InputBox("Ingrese su edad")
MsgBox mensaje [, icono, título]
Dim edad As Integer, edad = InputBox("Ingrese su edad")
edad = edad + 10, MsgBox "Dentro de 10 años su edad será: " & Str(edad)
Funciones y estructuras clave
Str: convierte un número en un carácter (texto).
Val: convierte el valor ingresado en el InputBox en un número.
If: permite la validación de datos.
GoTo: envía el programa nuevamente a un punto anterior (por ejemplo, para volver a pedir el dato).
Cómo ejecutar macros en Excel
Excel → Programador → Macros (nombre) → Grabar → Detener → Visual Basic
Ejemplo 1: Edad en 10 años
Dim edad As Integeredad = InputBox("Ingrese su edad")edad = edad + 10MsgBox "Dentro de 10 años su edad será" & Str(edad)
Ejecutar
Ejemplo 2: Validación con GoTo
Sub primer()Dim edad As Integervalida:edad = Val(InputBox("Ingrese su edad", "TÍTULO"))If edad = 0 ThenMsgBox "ERROR: INGRESE UN NÚMERO"GoTo validaEnd Ifedad = edad + 10MsgBox "Dentro de 10 años su edad será" & Str(edad)End Sub
Ejemplo 3: Determinar si un entero A es divisible por otro entero B
Sub primer()Dim a As Integer, b As Integera = Val(InputBox("Ingrese A", "TÍTULO"))b = Val(InputBox("Ingrese B", "TÍTULO"))If a Mod b = 0 ThenMsgBox Str(a) & " es divisible por " & Str(b)ElseMsgBox Str(a) & " NO es divisible por " & Str(b)End IfEnd Sub
Ejemplo 4: Estructura IF...THEN...ELSE (meses del año)
Número de los meses del año:
Sub primer()Dim N As Integervalida:N = Val(InputBox("Ingrese N"))If N = 1 ThenMsgBox "Enero"ElseIf N = 2 Then: MsgBox "Febrero"ElseIf N = 3 Then: MsgBox "Marzo"ElseIf N = 4 Then: MsgBox "Abril"ElseIf N = 5 Then: MsgBox "Mayo"ElseIf N = 6 Then: MsgBox "Junio"ElseIf N = 7 Then: MsgBox "Julio"ElseIf N = 8 Then: MsgBox "Agosto"ElseIf N = 9 Then: MsgBox "Septiembre"ElseIf N = 10 Then: MsgBox "Octubre"ElseIf N = 11 Then: MsgBox "Noviembre"ElseIf N = 12 Then: MsgBox "Diciembre"Else: MsgBox "Error de datos"GoTo validaEnd IfEnd Sub
Ejemplo 5: Otra forma con Select Case
Sub primer()Dim N As Integervalida:N = Val(InputBox("Ingrese N"))Select Case NCase 1: MsgBox "Enero"Case 2: MsgBox "Febrero"Case 3: MsgBox "Marzo"Case 4: MsgBox "Abril"Case 5: MsgBox "Mayo"Case 6: MsgBox "Junio"Case 7: MsgBox "Julio"Case 8: MsgBox "Agosto"Case 9: MsgBox "Septiembre"Case 10: MsgBox "Octubre"Case 11: MsgBox "Noviembre"Case 12: MsgBox "Diciembre"Case ElseMsgBox "Error de datos"GoTo validaEnd SelectEnd Sub
Funciones de redondeo y conversión
CInt: aproxima un número
Sub primer()Dim edad As Integeredad = Val(InputBox("Ingrese su edad", "TÍTULO"))edad = CInt(edad)MsgBox "Su edad será" & Str(edad)End Sub
Round: redondea indicando la cantidad de decimales
Sub primer()Dim edad As Doubleedad = Val(InputBox("Ingrese su edad", "TÍTULO"))edad = Round(edad, 1)MsgBox "Su edad será" & Str(edad)End Sub
Trabajo con planillas de Excel
Sub cajas()entrada = InputBox("Ingrese su nombre", "Cajas de entrada")Range("A1").SelectSelection.Formula = entradaentrada = InputBox("Ingrese edad", "Cajas de entrada")Range("B1").SelectSelection.Formula = entradaMsgBox ("Ingresaste nombre y edad")End Sub
Ejemplo completo: registro de notas de un alumno
Sub ejemplo()Dim nombre As StringDim nota1 As Integer, nota2 As Integer, nota3 As IntegerDim media As Singlenombre = InputBox("Entrada de nombre del alumno", "Nombre")valida:nota1 = Val(InputBox("Ingresar nota primera evaluación", "Nota"))If nota1 = 0 ThenMsgBox prompt:="En la casilla A1 no hay ningún valor numérico", Title:="Error"GoTo validaEnd Ifnota2 = Val(InputBox("Ingresar nota segunda evaluación", "Nota"))nota3 = Val(InputBox("Ingresar nota tercera evaluación", "Nota"))media = (nota1 + nota2 + nota3) / 3Range("A2").Value = nombreRange("B2").Value = nota1Range("C2").Value = nota2Range("D2").Value = nota3Range("E2").Value = mediaSelect Case mediaCase 0 To 2Range("F2").Value = "Muy deficiente"Case 3.1 To 4Range("F2").Value = "Deficiente"Case 4.1 To 5Range("F2").Value = "Suficiente"Case 5.1 To 6Range("F2").Value = "Notable"Case 6.1 To 7Range("F2").Value = "Sobresaliente"End SelectMsgBox ("Ingresaste nombre y notas")End Sub
Propiedades de formularios personalizados (UserForm)
Para cambiar el nombre del control, haga clic en Caption. Otras propiedades importantes:
- Font: fuente del texto.
- Text: almacena el contenido del cuadro de texto.
- Borrar:
" "(asigna un valor vacío).
Cambio de color y posición del TextBox
Private Sub CommandButton1_Click()EndEnd Sub
Private Sub CommandButton2_Click()TextBox1.Text = " "End Sub
Private Sub OptionButton1_Click()TextBox1.BackColor = vbBlueEnd Sub
Private Sub OptionButton2_Click()TextBox1.BackColor = vbRedEnd Sub
Private Sub OptionButton3_Click()TextBox1.BackColor = vbGreenEnd Sub
Private Sub OptionButton4_Click()TextBox1.BackColor = vbYellowEnd Sub
Private Sub OptionButton5_Click()TextBox1.Top = 0End Sub
Private Sub OptionButton6_Click()TextBox1.Top = 150End Sub
Limpieza de campos y cálculo con validación
Private Sub CommandButton1_Click()TextBox1.Text = " "TextBox2.Text = " "TextBox3.Text = " "End Sub
Private Sub CommandButton2_Click()If Val(TextBox2.Text) <= 0 ThenMsgBox ("ERROR DE DATOS")TextBox2.Text = " "ElseTextBox3.Text = (2 * Val(TextBox1.Text) / Val(TextBox2.Text))TextBox3.Locked = TrueEnd IfEnd Sub
Private Sub CommandButton3_Click()EndEnd Sub
Private Sub UserForm_Click()EndEnd Sub
Procedimiento con ponderación de notas
Sub PROCEDIMIENTO()Dim nombre As StringDim nota1 As Integer, nota2 As Integer, nota3 As IntegerDim media As Singlenombre = InputBox("Nombre del alumno")valida:nota1 = Val(InputBox("Nota 1"))If nota1 = 0 ThenMsgBox prompt:="ERROR DE NOTA", Title:="Error"GoTo validaEnd Ifnota2 = Val(InputBox("Nota 2"))nota3 = Val(InputBox("Nota 3"))media = ((nota1 * 0.3) + (nota2 * 0.3) + (nota3 * 0.4))Range("A2").Value = nombreRange("B2").Value = nota1Range("C2").Value = nota2Range("D2").Value = nota3Range("E2").Value = mediaSelect Case mediaCase 10 To 29Range("F2").Value = "Reprobado"Case 30 To 39Range("F2").Value = "Examen"Case 40 To 70Range("F2").Value = "Aprobado"End SelectMsgBox ("Ingresaste nombre y notas")End Sub