Está en la página 1de 40

Ejercicios en Visual Basic 6.

EJERCICIOS EN VISUAL BASIC 6.0

Los ejemplos que se desarrollan a continuacin estn escritos para Visual Basic 6.0.
Para adaptarlos a Visual Studio.Net y posteriores, se deben considerar algunos
puntos como los siguientes:

Algunos nombres por defecto de los controles cambiaron, por ejm:

Antes Ahora
Command1 Button1
Text1 TextBox1
Check1 CheckBox1
Frame1 GroupBox1
Picture1 PictureBox1
Option1 RadioButton1

Se recomienda al estudiante buscar las dems equivalencias entre los nombres de


los dems controles.

No existen las propiedades implcitas de los controles. Todas las propiedades


son explicitas, por ejm:

TextBox1.text = Valor
Label1.Text = Valor (Desaparece la propiedad Caption de los controles).

Los mtodos de los objetos han cambiado; sus parmetros se deben escribir
dentro de los parntesis, tal como las funciones predeterminadas, por ejm:

Antes Ahora
Text1.SetFocus TextBox1.Focus()
(Atrae el cursor a la caja de texto1)
Text1.Cls TextBox1.Clear()
(Borra el contenido de la caja de texto1)
(Es equivalente a: TextBox1.Text = "")

No es necesario escribir la instruccin Option Explicit por encima de todos


los procedimientos; por defecto las variables son explcitas. Esta situacin
puede modificarse en la pgina de propiedades del proyecto.

1) Altura del punto neutro en tuberas.

Option Explicit
Dim prof, WOB, WUdc, Densidad, ODdc, IDdc, XpuntoN As Single

Private Sub Command1_Click()


prof = Val(Text1)
1
Ejercicios en Visual Basic 6.0

WUdc = Val(Text2)
Densidad = Val(Text3)
ODdc = Val(Text4)
IDdc = Val(Text5)
WOB = Val(Text6)

XpuntoN = ((0.052 * Densidad * prof * (ODdc * ODdc - IDdc * IDdc) * 3.1416) / 4 +


WOB) / WUdc
Label8 = XpuntoN

End Sub

2) Aadir y eliminar elemento de una lista


Uso de Combo Box

Option Explicit
Private Sub AadirNuevoElemento_Click()
Dim NuevoElemento As String
NuevoElemento = InputBox("Introducir Frutas", "Nueva fruta")
If Len(Trim(NuevoElemento)) > 0 Then
ComboFrutas.AddItem NuevoElemento
End If
End Sub

Private Sub ComboFrutas_Click()


If ComboFrutas.ListIndex <> -1 Then
If ComboFrutas.Text <> "Ninguno" Then
Text1 = ComboFrutas.List(ComboFrutas.ListIndex)
Else
Text1 = ""
End If
End If
End Sub

Private Sub EliminarElemento_Click()


If ComboFrutas.ListIndex <> -1 Then
ComboFrutas.RemoveItem ComboFrutas.ListIndex
2
Ejercicios en Visual Basic 6.0

Text1 = ""
End If
End Sub

Private Sub ComboFrutas_Change()


Text1.Text = ComboFrutas.Text
End Sub

Private Sub Salir_Click()


End
End Sub

3) Planilla de pago
Uso de Combo Box

Option Explicit
Dim PagoHora, Horas, TotalPago As Single
Dim N As Integer
Private Sub Combo1_Click()
N = Combo1.ListIndex 'Almacena el ndice de la opcin seleccionada
Select Case N
Case 0
PagoHora = 15
LabelPagoHora = PagoHora
Case 1
PagoHora = 10
LabelPagoHora = PagoHora
Case 2
PagoHora = 5
LabelPagoHora = PagoHora
End Select
If Trim(TextHorasTrabajo) = "" Then
TextHorasTrabajo.SetFocus
Else
TotalPago = Format((Horas * PagoHora), "###,##0.00")
3
Ejercicios en Visual Basic 6.0

LabelTotalPago = TotalPago
End If
End Sub

Private Sub Nuevo_Click()


TextNombre = ""
LabelPagoHora = ""
TextHorasTrabajo = ""
Combo1.ListIndex = 0 '0=False, 1=True
Picture1.Visible = False
TextNombre.SetFocus
End Sub

Private Sub Salir_Click()


End
End Sub

Private Sub TextHorasTrabajo_Change()


If Trim(TextHorasTrabajo) = "" Or Val(TextHorasTrabajo) = 0 Then
Nuevo.Enabled = False
Else
Horas = Val(TextHorasTrabajo)
PagoHora = Val(LabelPagoHora)
TotalPago = Format((Horas * PagoHora), "###,##0.00")
LabelTotalPago = TotalPago
End If
End Sub

Private Sub TextNombre_Change()


If Trim(TextNombre) = "" Then
Nuevo.Enabled = 0 '0=False y 1=True
Picture1.Visible = 0
Else
Nuevo.Enabled = True
Picture1.Visible = True
End If
End Sub

4) Proforma para computadoras


Uso de Combo Box

4
Ejercicios en Visual Basic 6.0

Option Explicit
Dim PrecioComp, PrecioImp, SubTotal, Descuento, Total As Single
Dim N As Integer 'Almacenar el ndice de cada elemento

Private Sub CdoCalcular_Click()


SubTotal = PrecioComp + PrecioImp
LabSubTotal = Format(SubTotal, "###,##0.00")
Descuento = SubTotal * 0.13
LabIva = Format(Descuento, "###,##0.00")
Total = SubTotal - Descuento
LabTotal = Format(Total, "###,##0.00")
End Sub

Private Sub CdoNuevaProforma_Click()


Text1 = ""
Text2 = ""
ComboComputadoras.ListIndex = 0
ComboImpresoras.ListIndex = 0
LabPrecioComputadora = ""
LabPrecioImpresora = ""
LabSubTotal = ""
LabIva = ""
LabTotal = ""
Text1.SetFocus
End Sub

Private Sub CdoSalir_Click()


End
End Sub

Private Sub ComboComputadoras_Click()


N = ComboComputadoras.ListIndex
Select Case N
Case 0

5
Ejercicios en Visual Basic 6.0

PrecioComp = 850
LabPrecioComputadora = PrecioComp
Case 1
PrecioComp = 700
LabPrecioComputadora = PrecioComp
Case 2
PrecioComp = 600
LabPrecioComputadora = PrecioComp
End Select
End Sub

Private Sub ComboImpresoras_Click()


N = ComboImpresoras.ListIndex
Select Case N
Case 0
PrecioImp = 180
LabPrecioImpresora = PrecioImp
Case 1
PrecioImp = 270
LabPrecioImpresora = PrecioImp
Case 2
PrecioImp = 380
LabPrecioImpresora = PrecioImp
End Select
End Sub

Private Sub Form_Activate()


LabFecha = Date
End Sub

5) Sobre la consistencia de los datos

Private Sub Form1_Activate()


Text1 = ""
Text2 = ""
Text3 = ""
Text4 = ""
6
Ejercicios en Visual Basic 6.0

Text5 = ""
Command1.Enabled = False
Command2.Enabled = False
Text1.SetFocus
End Sub

Function Mayuscula(V)
If (V >= 65 And V <= 90) Then
Mayuscula = True
Else
Mayuscula = False
End If
End Function

Function Minuscula(V)
If (V >= 97 And V <= 122) Then
Minuscula = True
Else
Minuscula = False
End If
End Function

Function Numero(V)
If (V >= 40 And V <= 57) Then
Numero = True
Else
Numero = False
End If
End Function

Function Especial(V)
If V = 13 Or V = 32 Or V = 8 Or V = 255 Or V = 233 Or V = 237 Or V = 243 Or V =
250 Or V = 241 Or V = 209 Then
Especial = True
Else
Especial = False
End If
End Function

Function Ingresados()
If Trim(Text1) <> "" And IsDate(Text2) And Trim(Text3) <> "" And Trim(Text4) <> ""
And Trim(Text5) <> "" Then
Command1.Enabled = True
Command2.Enabled = True
Else
Command1.Enabled = False

7
Ejercicios en Visual Basic 6.0

Command2.Enabled = False
End If
End Function

Private Sub Command2_Click()


End
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)


Static EspacioAnterior As Boolean
If KeyAscii = 13 Then
Text2.SetFocus
End If
If KeyAscii = 32 Then
EspacioAnterior = True
Else
If Mayuscula(KeyAscii) Or Minuscula(KeyAscii) Or Especial(KeyAscii) Then
If Trim(Text1) = "" Or EspacioAnterior Then
'Convierte a Mayscula
KeyAscii = Asc(UCase(Chr(KeyAscii)))
Else
'Convierte a Minsculas
KeyAscii = Asc(LCase(Chr(KeyAscii)))
End If
EspacioAnterior = False
Else
MsgBox "Debe ingresar solo letras", 16, "Cuidado"
KeyAscii = 0 'Ignora el carcter digitado
Command1.Enabled = False
Command2.Enabled = False
End If
End If
End Sub

Private Sub Text2_LostFocus()


If IsDate(Text2) Then
Ingresados
Else
MsgBox "Debe ingresar una fecha correcta", 16, "Cuidado"
Text2.SelStart = 0
Text2.SelLength = Len(Text2)
Text2 = Text2.SelText
Text2.SetFocus
End If
End Sub

8
Ejercicios en Visual Basic 6.0

Private Sub Text2_KeyPress(KeyAscii As Integer)


If KeyAscii = 13 Then
Text3.SetFocus
End If
End Sub

Private Sub Text3_KeyPress(KeyAscii As Integer)


Dim Materia As String * 6
If KeyAscii = 13 Then
Text4.SetFocus
End If
If Mayuscula(KeyAscii) Or Minuscula(KeyAscii) Or Especial(KeyAscii) Then
Materia = UCase(Chr(KeyAscii))
If Trim(Text1) = "" Then
'Convierte a Mayscula
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End If
Else
MsgBox "Debe ingresar letras y numeros", 16, "Error"
Rem Ignora el carcter ingresado
KeyAscii = 0
Command1.Enabled = False
Command2.Enabled = False
End If
End Sub

Private Sub Text4_KeyPress(KeyAscii As Integer)


Dim Grupo As String * 2
If KeyAscii = 13 Then
Text5.SetFocus
Else
Grupo = UCase(Chr(KeyAscii))
If Grupo = "P" Or Grupo = "P1" Or Grupo = "P2" Or KeyAscii = 8 Then
Rem Convierte la letra ingresada en mayscula
KeyAscii = Asc(UCase(Chr(KeyAscii)))
Else
MsgBox "Debe ingresar solamente P, P1 o P2", 16, "Error"
Rem Ignora el carcter ingresado
KeyAscii = 0
Command1.Enabled = False
Command2.Enabled = False
End If
End If
End Sub

Private Sub Text5_KeyPress(KeyAscii As Integer)

9
Ejercicios en Visual Basic 6.0

If Numero(KeyAscii) Or KeyAscii = 8 Or KeyAscii = 13 Then


Ingresados
Else
MsgBox "Debe ingresar solo nmeros", 64, "Cuidado"
KeyAscii = 0
Command1.Enabled = False
Command2.Enabled = False
End If
End Sub

Private Sub Text5_Change()


If Val(Text5) < 0 Or Val(Text5) > 100 Then
MsgBox "La nota debe estar entre 0 y 100", 16, "Error"
Text5.SelStart = 0
Text5.SelLength = Len(Text5)
Text5 = Text5.SelText
Text5.SetFocus
Command1.Enabled = False
Command2.Enabled = False
Else
Ingresados
End If
End Sub

Private Sub Text1_Change()


Ingresados
End Sub

Private Sub Text4_Change()


Ingresados
End Sub

Private Sub Command1_Click()


Form1_Activate
End Sub

Private Sub Form1_Unload(Cancel As Integer)


Dim Respuesta As Integer
Respuesta = MsgBox("Est seguro de salir?", 36, "Cuidado")
If Respuesta = 7 Then
Rem Respondio SI
Cancel = True
End If
End Sub

6) Contadores y acumuladores

10
Ejercicios en Visual Basic 6.0

Option Explicit
Dim cd As Integer 'Cuenta los depsitos
Dim Saldo As Single

'Botn OK:
Private Sub Command1_Click()
Dim Deposito As Single
Deposito = Val(Text2)
Saldo = Saldo + Deposito 'Calcula el saldo
cd = cd + 1 'Cuenta el nmero de depsitos realiz.
Label5 = cd
Label6 = Saldo
Text2 = "" 'Borra solamente el depsito
Text2.SetFocus
End Sub

'Botn Nuevo Cliente:


Private Sub Command2_Click()
cd = 0
Saldo = 0
Text1 = ""
Text2 = ""
Label5 = ""
Label6 = ""
Text1.SetFocus
End Sub

Private Sub Command3_Click()


End
End Sub

7) Control direccional del pozo

11
Ejercicios en Visual Basic 6.0

Option Explicit
Dim Prof(), Azimut(), Tramo(), AngDesv() As Single
Dim I, N As Integer
Dim Rumbo, TVDparc, TVDacum As Single

'Se introducen los datos


Private Sub Command1_Click()
N = Val(Text1)
ReDim Prof(N), Azimut(N), Tramo(N), AngDesv(N)
MSFlexGrid1.Rows = N + 2
For I = 1 To N
Prof(I) = Val(InputBox("Introducir prof(" + Str(I) + "):", "Introducir datos
medidos"))
AngDesv(I) = Val(InputBox("Angulo Desv.(" + Str(I) + "):", "Introducir datos
medidos"))
Azimut(I) = Val(InputBox("Introducir Azimut(" + Str(I) + "):", "Introducir datos
medidos"))
MSFlexGrid1.TextMatrix(I, 1) = I
MSFlexGrid1.TextMatrix(I, 2) = Prof(I)
MSFlexGrid1.TextMatrix(I, 3) = AngDesv(I)
MSFlexGrid1.TextMatrix(I, 4) = Azimut(I)
Next I
End Sub

'Se calcula el rumbo


Private Sub Command2_Click()
For I = 1 To N
Select Case Azimut(I)
Case 0:
'Se calucula el rumbo
Rumbo = Azimut(I)
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
'Se determina la coordenada
MSFlexGrid1.TextMatrix(I, 6) = "N"
Case Is < 90:
12
Ejercicios en Visual Basic 6.0

Rumbo = Azimut(I)
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
MSFlexGrid1.TextMatrix(I, 6) = "NE"
Case 90:
Rumbo = 0
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
MSFlexGrid1.TextMatrix(I, 6) = "E"
Case Is < 180:
Rumbo = 180 - Azimut(I)
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
MSFlexGrid1.TextMatrix(I, 6) = "SE"
Case 180:
Rumbo = 0
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
MSFlexGrid1.TextMatrix(I, 6) = "S"
Case Is < 270:
Rumbo = Azimut(I) - 180
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
MSFlexGrid1.TextMatrix(I, 6) = "SW"
Case 270:
Rumbo = 0
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
MSFlexGrid1.TextMatrix(I, 6) = "W"
Case Is < 360:
Rumbo = 360 - Azimut(I)
MSFlexGrid1.TextMatrix(I, 5) = Rumbo
MSFlexGrid1.TextMatrix(I, 6) = "NW"
End Select
Next I

'Se calcula la profundidad vertical verdadera acumulada (TVD)


Tramo(1) = Prof(1)
'Se convierten los grados a radianes
AngDesv(1) = AngDesv(1) * 3.1416 / 180
TVDparc = Round(Tramo(1) * Cos(AngDesv(1)), 2)
'Round, en este caso redondea a 2 decimales
TVDacum = TVDparc
MSFlexGrid1.TextMatrix(1, 7) = TVDparc 'Parcial
MSFlexGrid1.TextMatrix(1, 8) = TVDparc 'Acumulada
For I = 2 To N
AngDesv(I) = AngDesv(I) * 3.1416 / 180
Tramo(I) = Prof(I) - Prof(I - 1)
TVDparc = Round(Tramo(I) * Cos(AngDesv(I)), 2)
MSFlexGrid1.TextMatrix(I, 7) = TVDparc
TVDacum = TVDacum + TVDparc
MSFlexGrid1.TextMatrix(I, 8) = TVDacum

13
Ejercicios en Visual Basic 6.0

Next I

End Sub

Private Sub Command3_Click()


End
End Sub

8) Determinacin de las coordenadas finales de un pozo

'Determinar las coordenadas finales totales de un pozo, conociendo


'los ngulos de desviacin vertical y su correspondiente profundidad
'medida.
Option Explicit
Dim N, I As Integer
Dim ProfM(), AngD(), PHV, PVV As Single
Dim Intervalo(), x, y As Single

Private Sub Command1_Click()


N = Val(InputBox("Introducir N de Datos", ""))
ReDim ProfM(N), AngD(N), Intervalo(N)
MSFlexGrid1.Rows = N + 1
For I = 1 To N
ProfM(I) = Val(InputBox("Prof (" + Str(I) + ")", ""))

AngD(I) = Val(InputBox("Angulo (" + Str(I) + ")", "")) * 3.14159 / 180


Next I

End Sub

14
Ejercicios en Visual Basic 6.0

Private Sub Command2_Click()


PHV = 0
PVV = 0

For I = 1 To N
Intervalo(I) = ProfM(I) - ProfM(I - 1)

x = Intervalo(I) * Sin(AngD(I))
y = Intervalo(I) * Cos(AngD(I))
PHV = PHV + x: PVV = PVV + y
'Print I, ProfM(I), AngD(I), Intervalo(I), x, y, PHV, PVV
MSFlexGrid1.TextMatrix(I, 0) = I
MSFlexGrid1.TextMatrix(I, 1) = ProfM(I)
MSFlexGrid1.TextMatrix(I, 2) = AngD(I)
MSFlexGrid1.TextMatrix(I, 3) = Intervalo(I)
MSFlexGrid1.TextMatrix(I, 4) = x
MSFlexGrid1.TextMatrix(I, 5) = y
MSFlexGrid1.TextMatrix(I, 6) = PHV
MSFlexGrid1.TextMatrix(I, 7) = PVV
Next I

End Sub

Private Sub Command3_Click()


LimpiarDatos
End Sub

Private Sub Command4_Click()


End
End Sub

Sub LimpiarDatos()
For I = 1 To N
MSFlexGrid1.TextMatrix(I, 0) = ""
MSFlexGrid1.TextMatrix(I, 1) = ""
MSFlexGrid1.TextMatrix(I, 2) = ""
MSFlexGrid1.TextMatrix(I, 3) = ""
MSFlexGrid1.TextMatrix(I, 4) = ""
MSFlexGrid1.TextMatrix(I, 5) = ""
MSFlexGrid1.TextMatrix(I, 6) = ""
MSFlexGrid1.TextMatrix(I, 7) = ""
Next I
End Sub

9) Planilla de pago
Con ElseIf

15
Ejercicios en Visual Basic 6.0

Option Explicit
Dim Nombre, Categoria As String
Dim Antiguedad As Byte
Dim TotalG, TotalD, LiquidoP As Single
Dim BonoC, BonoA As Single

Private Sub Calcular_Click()


Const Basico = 1000
Nombre = Text1
Categoria = Text2
Antiguedad = Val(Text3.Text)
If Categoria = "a" Then 'hhhhhhhhh
BonoC = Basico * 5 / 100
ElseIf Categoria = "b" Then
BonoC = Basico * 7 / 100
ElseIf Categoria = "C" Then
BonoC = Basico * 10 / 100
Else
End If
'Calculando el bono de antiguedad
If Antiguedad >= 20 Then
BonoA = Basico * 25 / 100
ElseIf Antiguedad >= 15 Then
BonoA = Basico * 20 / 100
ElseIf Antiguedad >= 10 Then
BonoA = Basico * 15 / 100
ElseIf Antiguedad >= 5 Then
BonoA = Basico * 10 / 100
Else
End If
TotalG = Basico + BonoC + BonoA

16
Ejercicios en Visual Basic 6.0

LabelTotalGanado.Caption = TotalG
TotalD = TotalG * (25.5 / 100)
LabelTotalDesc.Caption = TotalD
LiquidoP = TotalG - TotalD
LabelLiquidoPagable.Caption = LiquidoP
End Sub

Private Sub limpiar_Click()


Text1.Text = ""
Text2 = ""
Text3 = ""
LabelTotalGanado.Caption = ""
LabelTotalDesc = ""
LabelLiquidoPagable = ""
Text1.SetFocus
End Sub

Private Sub Salir_Click()


End
End Sub

10)Suma de dos nmeros

Private Sub Command1_Click()


Rem Label4.Caption = Val(Text1.Text) + Val(Text2.Text)
'calcula la suma de dos numeros
Label4 = Val(Text1) + Val(Text2)
Print "SE CALCULO TODO"
End Sub

Private Sub Command2_Click()


Text1.Text = ""
Text2.Text = ""
Label4.Caption = ""
Text1.SetFocus
End Sub

17
Ejercicios en Visual Basic 6.0

Private Sub Command3_Click()


End
End Sub

11) Clculo del factorial de un nmero usando Funciones

Option Explicit
Dim Numero As Integer
Dim F As Long

'En este procedimiento se define y se llama a la funcin Factorial( Numero) y se la


asigna
'a la variable F

Private Sub Calcular_Click()


Numero = Val(Text2)
F = Factorial(Numero)
Label3 = F
End Sub

'En este procedimiento se escribe el procedimiento Function a la que se hace


llamada en
'el procedimiento Calcular

Function Factorial(N) As Long


Factorial = 1
Do While N > 0
Factorial = Factorial * N
N=N-1
Loop
End Function

'En este procecimiento de formulario, se limpian la caja de texto2, la etiqueta3 y se


posiciona
18
Ejercicios en Visual Basic 6.0

'el cursor en la caja de texto2. El mtodo SetFocus funciona solo cuando el


formulario es
'activado y no cuando es cagado, como se muestra

Private Sub Form_Activate()


Text2 = ""
Label3 = ""
Text2.SetFocus
End Sub

Private Sub Salir_Click()


End
End Sub

12)Identificar el da de la semana utilizando ElseIf

Option Explicit
Dim Dia As Byte

Private Sub Command1_Click()


Dia = Val(Text1)
If Dia = 1 Then
Label2 = "Domingo"
ElseIf Dia = 2 Then
Label2 = "Lunes"
ElseIf Dia = 3 Then
Label2 = "martes"
ElseIf Dia = 4 Then
Label2 = "miercoles"
ElseIf Dia = 5 Then
Label2 = "jueves"
ElseIf Dia = 6 Then
Label2 = "viernes"
ElseIf Dia = 7 Then
Label2 = "sabado"
Else
Label2 = "no existe"
End If

19
Ejercicios en Visual Basic 6.0

End Sub

13)Calculo del promedio de notas con If anidadas.

Option Explicit
Dim Nombre As String
Dim N1, N2, N3, Prom, Asistencia As Single

Private Sub Calcular_Click()


Nombre = Text1
N1 = Val(Text2)
N2 = Val(Text3)
N3 = Val(Text4)
Asistencia = Val(Text5)
Prom = (N1 + N2 + N3) / 3
If Prom >= 51 And Asistencia >= 60 Then
Label7 = "Aprobado"
Else
Label7 = "Reprobado"
End If
'If Prom >= 51 Then
' If Asistencia >= 60 Then
' Label7 = "Aprobado"
' Else
' Label7 = "Reprobado"
' End If
'Else
' Label7 = "Reprobado"
' End If
Label6 = Prom

End Sub

20
Ejercicios en Visual Basic 6.0

Private Sub ComandoLimpiar_Click()


LimpiarDatos
End Sub

Private Sub Form_Activate()


LimpiarDatos
End Sub

Private Sub Salir_Click()


End
End Sub

Sub LimpiarDatos()
Text1 = ""
Text2 = ""
Text3 = ""
Text4 = ""
Text5 = ""
Label6 = ""
Label7 = ""
Text1.SetFocus
End Sub

14) Identificacin del da de la semana sin el botn calcular

Private Sub Text1_Change()


Dia_Semana
End Sub
Sub Dia_Semana()
If Text1 = 1 Then
Label2 = "Lunes"
End If

If Text1 = 2 Then
Label2 = "Martes"
End If

If Text1 = 3 Then
Label2 = "Miercoles"
End If

21
Ejercicios en Visual Basic 6.0

If Text1 = 4 Then
Label2 = "Jueves"
End If

If Text1 = 5 Then
Label2 = "Viernes"
End If

If Text1 = 6 Then
Label2 = "Sabado"
End If

If Text1 = 7 Then
Label2 = "Domingo"
End If

If Text1 < 1 Or Text1 > 7 Then


Label2 = "No existe"
End If
End Sub

15) Caracterizacin de la porosidad

Option Explicit
Dim Porosidad As Single
Private Sub Command1_Click()
Porosidad = Val(Text1)
If Porosidad <= 5 Then
Label2.Caption = "Porosidad baja"
Else
Label2 = "porosidad alta"
End If
End Sub

Private Sub Command2_Click()


End
End Sub

22
Ejercicios en Visual Basic 6.0

16) Venta de pasajes, con ListBox

Option Explicit
Dim Costo(5) As Single
Dim Precio, Descuento, Total As Single
Dim N As Integer 'Variable que contiene el ndice de cada elmento

Private Sub Nuevo_Click()


List1.ListIndex = 0
Check1.Value = 0
Text1 = ""
Text2 = ""
LabelPrecio = ""
LabelDescuento = ""
LabelTotal = ""
Text1.SetFocus
End Sub

'Al activar o desactivar el descuento, se visualicen los resultados


Private Sub Check1_Click()
If Check1 Then
Descontar 'Lladada al procedimiento Descontar
Else
Descuento = 0
LabelDescuento = Descuento
End If
CalcularTotal 'Llamada al procedimiento CalcularTotal
End Sub

'Se establecen los precios en el mismo orden de la lista


Private Sub Form_Activate()
Costo(0) = 100

23
Ejercicios en Visual Basic 6.0

Costo(1) = 70
Costo(2) = 120
Costo(3) = 30
Costo(4) = 80
End Sub

'Cuando se seleccione un elemento de la lista, aparecer el


'precio del pasaje respectivo, se consider el descuento y se
'obtendr el total a pagar.
Private Sub List1_Click()
N = List1.ListIndex
Precio = Costo(N)
LabelPrecio = Format(Precio, "##0.00")
If Check1 Then
Descontar
Else
Descuento = 0
LabelDescuento = Descuento
End If
CalcularTotal
End Sub

'Procedimiento general que calcula el descuento


Sub Descontar()
Descuento = Precio * 10 / 100
LabelDescuento = Format(Descuento, "##0.00")
End Sub

'Procedimiento que calcula el total a pagar


Sub CalcularTotal()
Total = Precio - Descuento
LabelTotal = Total
End Sub

Private Sub Salir_Click()


End
End Sub

17) Genera nmeros en una lista, a intervalos de 3, con ListBox

24
Ejercicios en Visual Basic 6.0

Option Explicit
Dim I, N As Integer

Private Sub Command1_Click()


N = Val(Text1)
List1.List(0) = "Lista"
For I = 1 To N Step 3
List1.AddItem I
Next I
End Sub

Private Sub Command2_Click()


List1.Clear
End Sub

Private Sub Command3_Click()


End
End Sub

18) Clculos con matrices, usando MsFlexGrid

25
Ejercicios en Visual Basic 6.0

Option Explicit
Dim M() As Integer
Dim Fila, Columna As Integer
Dim I, J As Integer
Dim Suma As Integer

Private Sub Command1_Click()


Fila = Val(Text1)
Columna = Val(Text2)
ReDim M(Fila, Columna)
For I = 1 To Fila 'Se introducen los elementos de la matriz
For J = 1 To Columna
M(I, J) = Val(InputBox("Elemento(" + Str(I) + "," + _
Str(J) + "):", "Introducir elementos"))
Next J
Next I
End Sub
Private Sub Command2_Click()
For I = 1 To Fila 'Se muestran los elementos de la matriz
For J = 1 To Columna
MSFlexGrid1.TextMatrix(I, J) = M(I, J)
Next J
Next I
End Sub
Private Sub Command3_Click()
Suma = 0
For I = 1 To Fila 'Suma la segunda columna
Suma = Suma + M(I, 2)
Next I
MSFlexGrid1.TextMatrix(Fila + 1, 1) = "Suma"
MSFlexGrid1.TextMatrix(Fila + 1, 2) = Suma
End Sub

Private Sub Command4_Click()


Text1 = "" 'Limpia datos de los controles
Text2 = ""
For I = 1 To Fila
For J = 1 To Columna
MSFlexGrid1.TextMatrix(I, J) = ""
Next J
Next I
MSFlexGrid1.TextMatrix(Fila + 1, 1) = ""
MSFlexGrid1.TextMatrix(Fila + 1, 2) = ""
End Sub

Private Sub Command5_Click()

26
Ejercicios en Visual Basic 6.0

End
End Sub

19) Control direccional del pozo utilizando MsFlexGrid

Option Explicit
Dim N, I As Integer
Dim Prof(), Angulo(), Tramo, ProfVV, DesvH As Single

Private Sub Command1_Click()


N = Val(Text1)
ReDim Prof(N), Angulo(N)
For I = 1 To N
Prof(I) = Val(InputBox("Introd. Prof.(" + Str(I) + "):", "Introducir datos"))
Angulo(I) = Val(InputBox("Introd. Angulo(" + Str(I) + "):", "Introducir datos"))
Next I
End Sub

Private Sub Command2_Click()


MSFlexGrid1.Rows = N + 1 'La 1era fila es ttulo
For I = 1 To N
Tramo = Prof(I) - Prof(I - 1)
ProfVV = Tramo * Cos(Angulo(I))
DesvH = Tramo * Sin(Angulo(I))
MSFlexGrid1.TextMatrix(I, 0) = I
MSFlexGrid1.TextMatrix(I, 1) = Prof(I)
MSFlexGrid1.TextMatrix(I, 2) = Angulo(I)
MSFlexGrid1.TextMatrix(I, 3) = Tramo
MSFlexGrid1.TextMatrix(I, 4) = ProfVV
MSFlexGrid1.TextMatrix(I, 5) = DesvH

Next I
End Sub

Private Sub Command3_Click()


27
Ejercicios en Visual Basic 6.0

LimpiarDatos
End Sub

Private Sub Command4_Click()


End
End Sub

Sub LimpiarDatos()
Text1 = ""
'MSFlexGrid1.Rows = 2
Text1.SetFocus
For I = 1 To N
MSFlexGrid1.TextMatrix(I, 0) = ""
MSFlexGrid1.TextMatrix(I, 1) = ""
MSFlexGrid1.TextMatrix(I, 2) = ""
MSFlexGrid1.TextMatrix(I, 3) = ""
MSFlexGrid1.TextMatrix(I, 4) = ""
MSFlexGrid1.TextMatrix(I, 5) = ""
Next I
End Sub

20) Ocultar y mostrar controles

Private Sub Command1_Click()


Label4.Caption = 0.052 * Val(Text1) * Val(Text2)
End Sub

Private Sub Command2_Click()


Text1.Text = ""
Text2 = ""
Text1.SetFocus
End Sub

Private Sub Command3_Click()

28
Ejercicios en Visual Basic 6.0

End
End Sub

Private Sub Command4_Click()


Text1.Visible = False
Text2.Visible = False
Label4.Visible = False
Command1.Visible = False
Command2.Visible = False
Command3.Visible = False
End Sub

Private Sub Command5_Click()


Text1.Visible = True
Text2.Visible = True
Label4.Visible = True
Command1.Visible = True
Command2.Visible = True
Command3.Visible = True
End Sub

21) Realizar las cuatro operaciones bsicas usando OptionButton y


ChekBox

Private Sub Check1_Click()


If Check1.Value = True Then
Text3.Font.Size = 16
End If
End Sub

Private Sub Check2_Click()


If Check2.Value = True Then
29
Ejercicios en Visual Basic 6.0

Text3.Font.Italic = True
Else
Text3.Font.Italic = False
End If
End Sub

Private Sub Check3_Click()


If Check3.Value = True Then
Text3.Font.Bold = True
End If
End Sub

Private Sub Command2_Click()


End
End Sub

Private Sub Form_Load()


Option1.Value = False
Option3.Value = False
Option2.Value = False
Option4.Value = False

End Sub

Private Sub Option1_Click()


If Option1.Value = True Then Text3 = Val(Text1) + Val(Text2)
End Sub

Private Sub Option2_Click()


If Option2.Value = True Then Text3 = Val(Text1) - Val(Text2)
End Sub

Private Sub Option3_Click()


If Option3.Value = True Then Text3 = Val(Text1) * Val(Text2)
End Sub

Private Sub Option4_Click()


If Option4.Value = True Then Text3 = Val(Text1) / Val(Text2)
End Sub

22) Cuatro operaciones bsicas usando OptionButton y ChekBox

30
Ejercicios en Visual Basic 6.0

'El mismo problema, sin agrupar los controles Check


Private Sub Command1_Click()
End
End Sub

Private Sub Check1_Click()


'El valor lgico True = 1
If Check1.Value = 1 Then
Label4.FontSize = 18
Else
Label4.FontSize = 8
End If
End Sub

Private Sub Check2_Click()


'La prop. Impcita de los Check es Value y su
'valor por defecto es True
If Check2 Then
Label4.FontBold = True
Else
Label4.FontBold = False
End If
End Sub

Private Sub Check3_Click()


If Check3 Then
Label4.FontItalic = True
Else
Label4.FontItalic = False
End If
End Sub
31
Ejercicios en Visual Basic 6.0

Private Sub Form_Load()


Option1.Value = False
Option2.Value = False
Option3.Value = False
Option4.Value = False
Check1.Value = False
Check1.Value = False
Check1.Value = False
End Sub

Private Sub Option1_Click()


If Option1.Value = True Then Label4 = Val(Text1) + Val(Text2)
End Sub

Private Sub Option2_Click()


'En esta instruccin se omite la prop. value por ser implcita, y
'el valor por defecto de esta propiedad es True
If Option2 Then Label4 = Val(Text1) - Val(Text2)
End Sub

Private Sub Option3_Click()


If Option3 Then Label4 = Val(Text1) * Val(Text2)
End Sub

Private Sub Option4_Click()


If Option4 Then Label4 = Val(Text1) / Val(Text2)
End Sub

23) Gradiente de formacin en funcin de la profundidad, usando variables


matriciales estticas

32
Ejercicios en Visual Basic 6.0

Option Explicit
Dim prof(1 To 5), grad(1 To 5), presion(1 To 5) As Single

Private Sub Calcular_Click()


prof(1) = Val(Text1): grad(1) = Val(Text6): presion(1) = prof(1) * grad(1): Label4 =
presion(1)
prof(2) = Val(Text2): grad(2) = Val(Text7): presion(2) = prof(2) * grad(2): Label5 =
presion(2)
prof(3) = Val(Text3): grad(3) = Val(Text8): presion(3) = prof(3) * grad(3): Label6 =
presion(3)
prof(4) = Val(Text4): grad(4) = Val(Text9): presion(4) = prof(4) * grad(4): Label7 =
presion(4)
prof(5) = Val(Text5): grad(5) = Val(Text10): presion(5) = prof(5) * grad(5): Label8 =
presion(5)

End Sub

Private Sub Command2_Click()


End
End Sub

Private Sub Form_Load()


Text1 = ""
Text2 = ""
Text3 = ""
Text4 = ""
Text5 = ""
Text6 = ""
Text7 = ""
Text8 = ""
Text9 = ""
Text10 = ""
Label4 = ""
Label5 = ""
Label6 = ""
Label7 = ""
Label8 = ""
End Sub

24) Calcular la hipotenusa de un tringulo usando un procedimiento


Function

33
Ejercicios en Visual Basic 6.0

Option Explicit
Dim Base, Altura, LadoC As Single

Private Sub Command1_Click()


Base = Val(Text1)
Altura = Val(Text2)
'Desde este procedimiento se llama a la funcin Hipotenusa y se le pasan
'como argumentos los dos valores introducidos, Base y Altura, los cuales
'sern tomados por las variables A y B, respectivamente.
LadoC = Hipotenusa(Base, Altura)
Label5 = LadoC
End Sub

'La funcin Hipotenusa recibe los valores Base y Altura y los copia
'en las variable A y B como dato de tipo Single.
Function Hipotenusa(A, B) As Single
'La funcin Hipotenusa realiza el clculo utilizando los valores
'copiados en las variables A y B.
Hipotenusa = Sqr(A * A + B * B)
End Function

'Nota: como la funcin Hipotenusa devuelve un valor, tambien se le asigna


'un tipo, el cual para este caso es tambien se Single (puede ser cualquier
'otro), aunque en el encabezado ya se defini el Tipo single para la
'variable LadoC, la cual tomar el valor calculado por la Funcion Hipotenusa.
'En caso de no definirse el tipo de dato para la Funcin, el valor devuelto
'ser de tipo Variant.

Private Sub Command2_Click()


End
End Sub

25) Determinacin de la constante a y la Pendiente m de una una


ecuacin lineal utilizando datos estadsticos (Regresin lineal)

34
Ejercicios en Visual Basic 6.0

Option Explicit
Dim SumaY, SumaX2, SumaXY, SumaX, A, m As Single
Dim I, N As Byte
Dim Y(), X() As Single

Private Sub calcular_Click()


SumaY = 0
SumaX = 0
SumaX2 = 0
SumaXY = 0
For I = 1 To N
SumaY = SumaY + Y(I)
SumaX = SumaX + X(I)
SumaX2 = SumaX2 + X(I) * X(I)
SumaXY = SumaXY + X(I) * Y(I)
Next I
A = (SumaY * SumaX2 - SumaXY * SumaX) / (N * SumaX2 - SumaX * SumaX)
m = (SumaY) / (SumaX) - (N * A) / SumaX
LabelA = A
LabelM = m

End Sub

Private Sub IntroDatos_Click()


N = Val(Text1)
ReDim Y(N), X(N)

For I = 1 To N
Y(I) = Val(InputBox("Introducir Y(i)", "Inroducir datos"))
X(I) = Val(InputBox("Introducir X(i)", "Inroducir datos"))
Next I

End Sub

Private Sub salir_Click()


End

35
Ejercicios en Visual Basic 6.0

End Sub

26) Construir una tabla de presiones directamente en el formulario


utilizando la sentencia Print

Option Explicit
Dim Prof(), Densidad, Presion As Single
Dim I, N As Integer 'Contador de las profundidades
'En este programa se introducen las profundidades (crecientes) para el calculo
'de presiones. La densidad variara entre 8 y 10 a intervalos de 0.5.
'N representa la cantidad de datos de profundidades, para construir la tabla
'de presiones respecto a Prof vs Densidad.

Private Sub Command1_Click()


N = Val(Text1)

ReDim Prof(N)
Print "Prof", "d=8", "d=8.5", "d=9", "d=9.5", "d=10" 'Se imprimen los titulos
Print
"________________________________________________________________"

For I = 1 To N
Prof(I) = Val(InputBox("Introducir Prof" + Str(I) + ":", "Introducir datos"))
Print Prof(I), 'La coma hace que se impriman los datos siguietes en esta linea
For Densidad = 8 To 10 Step 0.5
Presion = 0.052 * Densidad * Prof(I)
Print Presion, 'La como hace que se impriman los datos de presion
seguidamente
Next Densidad
Print 'Inserta una nueva linea para imprimir la siguiente fila de P
Next I
End Sub

Private Sub Command2_Click()


End
End Sub

27) Uso de mltiples formularios para el clculo de las propiedades de los


gases

36
Ejercicios en Visual Basic 6.0

Private Sub Command1_Click()


FormBienvenida.Hide
FormDatosPer.Show
End Sub

Private Sub Command2_Click()


Dim R As Integer
R = MsgBox("Est seguro?", 36, "Cuidado")
If R = 6 Then End
End Sub

37
Ejercicios en Visual Basic 6.0

Private Sub Command1_Click()


Dim R As Integer
If Text2 = "visual" Then 'Se toman en cuenta maysc y minsc
FormDatosPer.Hide
FormOpcionCalculo.Show
Else
R = MsgBox("Clave incorrecta", 16 + 5, "Acceso denegado")
If R = 4 Then
LimpiarDatos
Else
End
End If
End If
End Sub

Private Sub CommandCancelar_Click()


LimpiarDatos
End Sub

Private Sub CmdoSalir_Click()


End
End Sub

Sub LimpiarDatos()
Text1 = ""
Text2 = ""
Text1.SetFocus
End Sub

38
Ejercicios en Visual Basic 6.0

Private Sub Form_Load()


Option1.Value = True
Option3.Value = 1
End Sub

Private Sub Option2_Click()


If Option2 Then
'Se inabilitan los cotroles del marco2
Frame2.Enabled = False
Option3.Value = False
Option3.Enabled = False
Option4.Value = False
Option4.Enabled = False
End If
End Sub

Private Sub Option1_Click()


'Se habilitan los controles del marco2
If Option1 Then
Option3.Value = True
Frame2.Enabled = True
Option3.Enabled = True
Option4.Enabled = True
End If
End Sub

Private Sub ComContinuar_Click()


If Option2 Then
FormOpcionCalculo.Hide
FormGE.Show
ElseIf Option3 Then
FormOpcionCalculo.Hide
39
Ejercicios en Visual Basic 6.0

FormFracciones7.Show
ElseIf Option4 Then
FormOpcionCalculo.Hide
FormFracciones10.Show
Else
End If
End Sub

Private Sub Command2_Click()


End
End Sub

40

También podría gustarte