Está en la página 1de 19

CUADERNO DE

EJERCICIOS Y PRACTICAS
VISTUAL BASIC

01

INTRODUCCION
Bienvenido al curso de Visual Basic, este cuaderno de ejercicios y practicas complementa su Guia de
Estudio (apoyo teorico) para que realice los ejercicios correspondientes segn se los vaya presentando
su profesor.
Todos los ejercicios y practicas fueron realizadas con MS Visual Basic 6.0. Los ejercicios son expuestos
paso a paso y al final contienen algunas preguntas que deben ser contestadas. Las practicas por lo
general no contienen la solucion en este cuaderno para que el alumno las desarrolle por su cuenta.

02

Ejercicio 1 Unidades de Temperatura


Se trata se realizar un programa sencillo que muestre la equivalencia entre las escalas de temperaturas
en grados centigrados y grados Fahrenheit. En el centro del formulario aparece una barra de
desplazamiento vertical que permite desplazarse con incrementos pequeos de 1. C y grandes de 10.
C. Como es habitual, tambien puede cambiarse el valor arrastrando con el raton el cursor de la barra.
Los valores maximos y minimos de la barra son 100 C y -100 C.
A ambos lados de la barra aparcen dos cuadros de texto donde aparecen los grados correspondientes a
la barra en ambas ecalas. Encima aparecen dos rotulos (labels) que indican la escala de temperaturas
correspondiente. Completan la aplicacin un boton SALIR que termina la ejecucion y un menu FILE con
la unica opcion SALIR, que termina asimismo la ejecucion del programa.
La tabla a continuacion indica los controles utilizados en este ejemplo junto con las propiedades y los
valores correspondientes
CONTROL
frmTemp

mnuFile
mnuFileSalir
cmdSalir
txtCent
txtFahr
vsbTemp

lblCent

lblFahr

PROPIEDAD
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
text
Name
text
Name
Min
Max
SmallChange
LargeChange
Value
Name
Caption
Font
Name
Caption
Font

VALOR
frmTemp
Conversor de Temperaturas
mnuFile
&Archivo
mnuFileSalir
&Salida
cmdSalir
Salir
txtCent
0
txtFahr
32
vsbTemp
100
-100
1
10
0
lblCent
Grados Centigrados
MS Sans Serif, 10
lblFahr
Grados Fahrenheit
MS Sans Serif, 10

Y el codigo del programa es el siguiente:

03

Option Explicit
Private Sub cmdSalir_Click()
Beep
End
End Sub
Private Sub mnuFileExit_Click()
End
End Sub
Private Sub vsbTemp_Change()
txtCent.text = vsbTemp.value
txtFahr.text = 32 + 1.8 * vsbTemp.value
End Sub

04

Responde a lo siguiente:
PREGUNTA
Que son los controles en Visual Basic?
Cules son los controles que usamos en este
programa?
Cmo ponemos nombre a nuestros controles?
Cmo ponemos un valor de texto a nuestros
controles?
Cul es la instruccin o comando que termina el
programa?
Dnde ponemos el codigo del programa?

RESPUESTA
Son los objetos visuales que representan elementos y
tienen propiedades, eventos y metodos
El ScrollBar Vertiical, la caja de texto, la etiqueta y el
boton de comando
Con la propiedad NAME
Con la propiedad Caption, Text o Value
END

En el editor de codigo haciendo doble click en el


control

Ejemplo 2 Colores y posiciones


Ahora se presenta un sencillo ejemplo que permite mover una caja de texto por la pantalla,
permitiendo a su vez representarla con cuatro colores diferentes.
Los archivos se llamaran Colores0.vbp y Colores0.frm
CONTROL
frmColores0

fraColores
optAzul
optRojo
optAmarillo
optVerde
fraPosicion
optArriba
optAbajo

PROPIEDAD
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption

VALOR
frmColores0
Colores
fraColor
Colores
optAzul
Azul
optRojo
Rojo
optAmarillo
Amarillo
optVerde
Verde
fraPosicion
Posicion
optArriba
Arriba
optAbajo
Abajo

05

txtCaja

Name
Text

txtCaja

Y el codigo es:
Option Explicit
Private Sub Form_Load()
txtCaja.Top = 0
End Sub

Private Sub optArriba_Click()


txtCaja.Top = 0
End Sub
Private Sub optAbajo_Click()
txtCaja.Top = frmColores0.ScaleHeight txtCaja.Height
End Sub
Private Sub optAzul_Click()
txtCaja.BackColor = vbBlue
End Sub
Private Sub optRojo_Click()
txtCaja.BackColor = vbRed
End Sub
Private Sub optVerde_Click()
txtCaja.BackColor = vbGreen
End Sub
Private Sub optAmarillo_Click()
txtCaja.BackColor = vbYellow
End Sub

06

Responde a lo siguiente:
PREGUNTA
Cules son las propiedades de la caja de texto que
estamos usando en este programa?
Qu otros controles estamos viendo en este
ejercicio?
Cmo cambiamos el color de fondo de control de
textbox?

RESPUESTA
Top y BackColor
Frame y Option
Con la propiedad BackColor

07

Ejercicio 3 MiniCalculadora
En este ejemplo se muestra una calculadora elemental que permite hacer las cuatro operaciones
aritmeticas. Los archivos de este proyecto se pueden llamar minicalc.vbp y minicalc.frm
CONTROL
Form

textbox
textbox
textbox
label
label
CommandButton
CommandButton
CommandButton
CommandButton

PROPIEDAD
Name
Caption
Name
Text
Name
Text
Name
Text
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption

VALOR
frmMinicalc
Minicalculadora
txtOper1
txtOper2
txtResult
lblOp
lblEqual
=
cmdSuma
+
cmdResta
cmdMulti
*
cmdDiv
/

Y a continuacion se muestra el codigo correspondiente a los procedimientos


Option Explicit

Private Sub cmdDiv_Click()


txtResult.Text = val(txtOper1.Text) / val(txtOper2.text)
lblOp.Caption = /
End Sub
Private Sub cmdProd_Click()
txtResult.Text = val(txtOper1.Text) * val(txtOper2.text)
lblOp.Caption = *
End Sub
Private Sub cmdDiv_Click()
txtResult.Text = val(txtOper1.Text) / val(txtOper2.text)
lblOp.Caption = /
End Sub

08

Private Sub cmdResta_Click()


txtResult.Text = val(txtOper1.Text) - val(txtOper2.text)
lblOp.Caption = -
End Sub
Private Sub cmdSuma_Click()
txtResult.Text = val(txtOper1.Text) + val(txtOper2.text)
lblOp.Caption = +
End Sub

Responde a lo siguiente:
PREGUNTA
Para que usamos la funcion VAL() de VisualBasic?

Qu operaciones estamos realizando?


Dnde ponemos el codigo que realiza las
operaciones?

RESPUESTA
Para convertir las letras de las cajas de texto en
numeros y poder realizar las opereaciones
Suma, resta, multiplicacion y division
En cada uno de los botones de comandos, en el
evento CLICK()

09

Ejercicios de Visual Basic

Ejercicio 1

Dim saludo As String * 10


Private Sub Command1_Click()
Dim Nombre As String * 10
Nombre = "Joaquim"
saludo = "HOLA"
Print saludo; y; Nombre
End Sub
Private Sub Command2_Click()
saludo = "ADIOS"
Print saludo
End Sub
Ejercicio 2

10

Ejercicios de Visual Basic

Private Sub Boton_dividir_Click()


Dim result As Integer
result = Val(Numero_uno.Text) / Val(Numero_dos.Text)
Numero_resultado.Text = Str(result)
End Sub
Private Sub Boton_multiplicar_Click()
Dim result As Integer
result = Val(Numero_uno.Text) * Val(Numero_dos.Text)
Numero_resultado.Text = Str(result)
End Sub
Private Sub Boton_restar_Click()
Dim result As Integer
result = Val(Numero_uno.Text) - Val(Numero_dos.Text)
Numero_resultado.Text = Str(result)
End Sub
Private Sub Boton_salir_Click()
End
End Sub
Private Sub Boton_Sumar_Click()
Dim result As Integer
result = Val(Numero_uno.Text) + Val(Numero_dos.Text)
Numero_resultado.Text = Str(result)
End Sub
Ejercicio 3

11

Ejercicios de Visual Basic

Private Sub Command1_Click()


Dim result, resulta As Double
result = Val(Text1.Text) * (60)
Text2.Text = Str(result)
resulta = Val(Text2.Text) * (60)
Text3.Text = Str(resulta)
End Sub
Private Sub Command2_Click()
End
End Sub
Ejercicio 4

Private Sub Azul_Click()


Texto.ForeColor = &HFF0000
End Sub
Private Sub Command1_Click()
End
End Sub
Private Sub Cursiva_Click()
Texto.FontItalic = True
Texto.FontBold = False
End Sub
Private Sub Form_Load()
Normal.Value = True
Azul.Value = True
Texto.FontBold = False
Texto.FontItalic = False
Texto.ForeColor = &HFF0000
End Sub

12

Ejercicios de Visual Basic

Private Sub Negrilla_Click()


Texto.FontBold = True
Texto.FontItalic = False
End Sub
Private Sub Normal_Click()
Texto.FontBold = False
Texto.FontItalic = False
End Sub
Private Sub Verde_Click()
Texto.ForeColor = &HFF00&
End Sub
Ejercicio 5

Private Sub Ape_GotFocus()


Ape.SelStart = 0
Ape.SelLength = Len(Ape.Text)
End Sub
Private Sub Boton_aadir_Click()
totalregistros = totalregistros + 1
If totalregistros > 50 Then
MsgBox "losta completa", 16, "error"
Else
agenda(totalregistros).Nombre = Nom.Text
agenda(totalregistros).apellidos = Ape.Text
agenda(totalregistros).telefono = Tel.Text
agenda(totalregistros).Edad = Val(Edad.Text)
Lista_1.AddItem Nom.Text
Lista_2.AddItem Nom.Text
End If
Nom.SetFocus
End Sub
4

13

Ejercicios de Visual Basic

Private Sub Boton_eliminar_Click(Index As Integer)


Dim I, B As Integer
For I = 1 To totalregistros
If (RTrim$(Lista_1.Text) = RTrim$(agenda(I).Nombre)) Then
Exit For
End If
Next I
Nom.Text = agenda(I).Nombre
Ape.Text = agenda(I).apellidos
Tel.Text = agenda(I).telefono
Edad.Text = Str(agenda(I).Edad)
B = MsgBox("Eliminar Registro:" + Nom.Text, 3 + 32, "Eliminar")
If B = 6 Then
Lista_1.RemoveItem I - 1
totalregistros = totalregistros - 1
For j = I To totalregistros
agenda(j).Nombre = agenda(j + 1).Nombre
agenda(j).apellidos = agenda(j + 1).apellidos
agenda(j).telefono = agenda(j + 1).telefono
agenda(j).Edad = agenda(j + 1).Edad
Next j
Nom.Text = ""
Ape.Text = ""
Tel.Text = ""
Edad.Text = ""
End If
End Sub
Private Sub Boton_fin_Click(Index As Integer)
End
End Sub
Private Sub Eda_GotFocus()
Eda.SelStart = 0
Eda.SelLength = Len(Eda.Text)
End Sub
Private Sub Form_Load()
totalregistros = 0
End Sub
Private Sub Lista_2_Change()
Dim n As Integer
n = Lista_2.ListIndex + 1
Nom.Text = agenda(n).Nombre
Ape.Text = agenda(n).apellidos
Tel.Text = agenda(n).telefono
Eda.Text = agenda(n).Edad
End Sub

14

Ejercicios de Visual Basic

Private Sub Nom_GotFocus()


Nom.SelStart = 0
Nom.SelLength = Len(Nom.Text)
End Sub
Private Sub Tel_GotFocus()
Tel.SelStart = 0
Tel.SelLength = Len(Nom.Text)
End Sub
Crear un mdulo
Type registro
Nombre As String * 15
apellidos As String * 25
telefono As String * 15
Edad As String * 3
End Type
Global agenda(1 To 50) As registro
Global totalregistros As Integer
Ejercicio 6

Private Sub Boton_fin_Click()


End
End Sub
Private Sub cd_Click()
Dim precio As Long
Dim res As Long
precio = 0
res = 0
If cd.Value = 1 Then
precio = Val(suplemento.Caption) + 20000
Else
precio = Val(suplemento.Caption) = -20000
End If
6

15

Ejercicios de Visual Basic

suplemento.Caption = precio
res = Val(suplemento.Caption) + Val(Total.Caption)
PVP.Caption = res
End Sub
Private Sub Form_Load()
Total.Alignment = 1
suplemento.Alignment = 1
PVP.Alignment = 1
suplemento.Caption = "0"
End Sub
Private Sub kit_Click()
Dim precio As Long
Dim res As Long
precio = 0
res = 0
If kit.Value = 1 Then
precio = Val(suplemento.Caption) + 35000
Else
precio = Val(suplemento.Caption) = -35000
End If
suplemento.Caption = precio
res = Val(suplemento.Caption) + Val(Total.Caption)
PVP.Caption = res
End Sub
Private Sub pantalla_Click()
Dim precio As Long
Dim res As Long
precio = 0
res = 0
If pantalla.Value = 1 Then
precio = Val(suplemento.Caption) + 120000
Else
precio = Val(suplemento.Caption) = -120000
End If
suplemento.Caption = precio
res = Val(suplemento.Caption) + Val(Total.Caption)
PVP.Caption = res
End Sub
Private Sub Ram_Click()
Dim precio As Long
Dim res As Long
precio = 0
res = 0
If Ram.Value = 1 Then
precio = Val(suplemento.Caption) + 80000

16

Ejercicios de Visual Basic

Else
precio = Val(suplemento.Caption) = -80000
End If
suplemento.Caption = precio
res = Val(suplemento.Caption) + Val(Total.Caption)
PVP.Caption = res
End Sub
Ejercicio 7

Private Sub icono_1_Click()


Imagen.Picture = LoadPicture("C:\Archivos de programa\Microsoft Visual
Studio\Common\Graphics\Metafile\Business\computer.wmf")
End Sub
Private Sub icono_2_Click()
Imagen.Picture = LoadPicture("C:\Archivos de programa\Microsoft Visual
Studio\Common\Graphics\Metafile\Business\disk35.wmf")
End Sub
Private Sub icono_3_Click()
Imagen.Picture = LoadPicture("C:\Archivos de programa\Microsoft Visual
Studio\Common\Graphics\Metafile\Business\phone.wmf")
End Sub
Ejercicio 8
Dim n As Integer
Private Sub btnBorrar_Click()
If n = 0 Then
MsgBox "Minimo 1 linea", 16, "Error"
Exit Sub
End If
8

17

Ejercicios de Visual Basic

Unload txtRef(n)
Unload txtDes(n)
Unload txtCan(n)
Unload txtPre(n)
n=n-1
End Sub

Private Sub btnFin_Click()


Unload Me
End Sub
Private Sub btnImprimir_Click()
Dim i As Integer
Printer.FontName = "Arial"
Printer.FontSize = "10"
For i = 0 To Principal.Count - 1
If TypeOf Controls(i) Is TextBox Then
GoSub posicin
Printer.Font .Underline = False
Printer.Print Controls(i).Text
End If
If TypeOf Controls(i) Is Label Then
GoSub posicin
Printer.Font .Underline = True
Printer.PrintQuality Controls(i).Caption
End If
Next i
Printer.EndDoc
Exit Sub
posicin:
Printer.CurrentX = Controls(i).Left

18

Ejercicios de Visual Basic

Printer.CurrentY = Controls(i).Top
Return
End Sub
Private Sub btnNueva_Click()
n=1
If n > 4 Then
MsgBox "Albarn completo", 16, "Error"
n=4
Exit Sub
End If
'Referencia
Load txtRef(n)
txtRef(n).Top = txtRef(n - 1).Top + 350
txtRef(n).Visible = True
txtRef(n).Text = ""
'Descripcin
Load txtDes(n)
txtDes(n).Top = txtDes(n - 1).Top + 350
txtDes(n).Visible = True
txtDes(n).Text = ""
'Precio
Load txtPre(n)
txtPre(n).Top = txtPre(n - 1).Top + 350
txtPre(n).Visible = True
txtPre(n).Text = ""
'Cantidad
Load txtCan(n)
txtCan(n).Top = txtCan(n - 1).Top + 350
txtCan(n).Visible = True
txtCan(n).Text = ""
End Sub
Private Sub Form_Load()
n=0
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
Dim Msg
Msg = "Desea salir de la aplicacin?"
If MsgBox(Msg, 36, Me.Caption) = 7 Then
Cancel = True
End If
End Sub

19

También podría gustarte