Elementos Básicos de Visual Basic: Tutorial Práctico con Ejemplos de InputBox, MsgBox, IF y Select Case en Excel

Otras lenguas extranjeras11,46 KB

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 Integer
edad = InputBox("Ingrese su edad")
edad = edad + 10
MsgBox "Dentro de 10 años su edad será" & Str(edad)



Ejecutar





Ejemplo 2: Validación con GoTo



Sub primer()
Dim edad As Integer
valida:
edad = Val(InputBox("Ingrese su edad", "TÍTULO"))
If edad = 0 Then
MsgBox "ERROR: INGRESE UN NÚMERO"
GoTo valida
End If
edad = edad + 10
MsgBox "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 Integer
a = Val(InputBox("Ingrese A", "TÍTULO"))
b = Val(InputBox("Ingrese B", "TÍTULO"))
If a Mod b = 0 Then
MsgBox Str(a) & " es divisible por " & Str(b)
Else
MsgBox Str(a) & " NO es divisible por " & Str(b)
End If
End Sub





Ejemplo 4: Estructura IF...THEN...ELSE (meses del año)



Número de los meses del año:



Sub primer()
Dim N As Integer
valida:
N = Val(InputBox("Ingrese N"))
If N = 1 Then
MsgBox "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 valida
End If
End Sub



Ejemplo 5: Otra forma con Select Case



Sub primer()
Dim N As Integer
valida:
N = Val(InputBox("Ingrese N"))
Select Case N
Case 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 Else
MsgBox "Error de datos"
GoTo valida
End Select
End Sub





Funciones de redondeo y conversión



CInt: aproxima un número



Sub primer()
Dim edad As Integer
edad = 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 Double
edad = 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").Select
Selection.Formula = entrada
entrada = InputBox("Ingrese edad", "Cajas de entrada")
Range("B1").Select
Selection.Formula = entrada
MsgBox ("Ingresaste nombre y edad")
End Sub



Ejemplo completo: registro de notas de un alumno



Sub ejemplo()
Dim nombre As String
Dim nota1 As Integer, nota2 As Integer, nota3 As Integer
Dim media As Single

nombre = InputBox("Entrada de nombre del alumno", "Nombre")
valida:
nota1 = Val(InputBox("Ingresar nota primera evaluación", "Nota"))
If nota1 = 0 Then
MsgBox prompt:="En la casilla A1 no hay ningún valor numérico", Title:="Error"
GoTo valida
End If
nota2 = Val(InputBox("Ingresar nota segunda evaluación", "Nota"))
nota3 = Val(InputBox("Ingresar nota tercera evaluación", "Nota"))
media = (nota1 + nota2 + nota3) / 3
Range("A2").Value = nombre
Range("B2").Value = nota1
Range("C2").Value = nota2
Range("D2").Value = nota3
Range("E2").Value = media
Select Case media
Case 0 To 2
Range("F2").Value = "Muy deficiente"
Case 3.1 To 4
Range("F2").Value = "Deficiente"
Case 4.1 To 5
Range("F2").Value = "Suficiente"
Case 5.1 To 6
Range("F2").Value = "Notable"
Case 6.1 To 7
Range("F2").Value = "Sobresaliente"
End Select

MsgBox ("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()
End
End Sub



Private Sub CommandButton2_Click()
TextBox1.Text = " "
End Sub



Private Sub OptionButton1_Click()
TextBox1.BackColor = vbBlue
End Sub



Private Sub OptionButton2_Click()
TextBox1.BackColor = vbRed
End Sub



Private Sub OptionButton3_Click()
TextBox1.BackColor = vbGreen
End Sub



Private Sub OptionButton4_Click()
TextBox1.BackColor = vbYellow
End Sub



Private Sub OptionButton5_Click()
TextBox1.Top = 0
End Sub



Private Sub OptionButton6_Click()
TextBox1.Top = 150
End 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 Then
MsgBox ("ERROR DE DATOS")
TextBox2.Text = " "
Else
TextBox3.Text = (2 * Val(TextBox1.Text) / Val(TextBox2.Text))
TextBox3.Locked = True
End If
End Sub



Private Sub CommandButton3_Click()
End
End Sub



Private Sub UserForm_Click()
End
End Sub





Procedimiento con ponderación de notas



Sub PROCEDIMIENTO()

Dim nombre As String
Dim nota1 As Integer, nota2 As Integer, nota3 As Integer
Dim media As Single

nombre = InputBox("Nombre del alumno")
valida:
nota1 = Val(InputBox("Nota 1"))
If nota1 = 0 Then
MsgBox prompt:="ERROR DE NOTA", Title:="Error"
GoTo valida
End If
nota2 = Val(InputBox("Nota 2"))
nota3 = Val(InputBox("Nota 3"))
media = ((nota1 * 0.3) + (nota2 * 0.3) + (nota3 * 0.4))
Range("A2").Value = nombre
Range("B2").Value = nota1
Range("C2").Value = nota2
Range("D2").Value = nota3
Range("E2").Value = media
Select Case media
Case 10 To 29
Range("F2").Value = "Reprobado"
Case 30 To 39
Range("F2").Value = "Examen"
Case 40 To 70
Range("F2").Value = "Aprobado"

End Select
MsgBox ("Ingresaste nombre y notas")
End Sub

Descargar

PDF Word HTML