103
UNIVERSIDA NACIONAL ABIERTA Y A DISTANCIA PROGRAMA INGENIERIA DE SISTEMAS ASIGNACION PROGRAMACION VISIAL BASIC BASICO ELABORADO POR: CESAR ORLANDO JIMENEZ ANGARITA

Talleres Visual Basic Basico 2[1]

Embed Size (px)

Citation preview

Page 1: Talleres Visual Basic Basico 2[1]

UNIVERSIDA NACIONAL ABIERTA Y A DISTANCIA

PROGRAMA INGENIERIA DE SISTEMAS

ASIGNACION PROGRAMACION VISIAL BASIC BASICO

ELABORADO POR:CESAR ORLANDO JIMENEZ ANGARITA

CIENCIAS BASICAS TECNOLOGIA E INGENIERIAINGENIERIA DE SISTEMAS

SANTA FE DE BOGOTA D.C. AGOSTO DE 2007

Page 2: Talleres Visual Basic Basico 2[1]

1.Primer Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Label1 Caption = CapitalLabel2 Caption = % de InteresesLabel3 Caption = Interes ProducidoLabel4 Caption = Capital AcumuladoTextBox1 Nombre = CapitalTextBox2 Nombre = TpInteresTextBox3 Nombre = InteresProTextBox4 Nombre = CapitalAcCommandbotton1 Nombre = CalcularForm Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Calcular_Click() Dim cap As Double, tp As Double Dim formato As String formato = "#,###,###,##0.00" cap = Capital.Text tp = TpInterés.Text 'Cálculos redondeando resultados InterésPro.Text = Format(Int(cap * tp / 100 + 0.5), formato) CapitalAc.Text = Format(cap + InterésPro.Text, formato)End Sub---------------------------------------------------------------------------Private Sub Capital_Change()End Sub---------------------------------------------------------------------------Private Sub CapitalAc_Change()End Sub---------------------------------------------------------------------------Private Sub Form_Load()End Sub---------------------------------------------------------------------------Private Sub InterésPro_Change()End Sub---------------------------------------------------------------------------Private Sub Label1_Click()

Page 3: Talleres Visual Basic Basico 2[1]

End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub Label4_Click()End Sub---------------------------------------------------------------------------Private Sub TpInterés_Change()End Sub

Page 4: Talleres Visual Basic Basico 2[1]

2.Segundo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Label1 Caption = Grados CentigradosLabel2 Caption = Grados FahvenheitTextBox1 Nombre = Grados_CTextBox2 Nombre = Grados_FCommandbotton1 Nombre = FahvenheitCommandbotton2 Nombre = CentigradosForm Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load() Grados_C.Text = "0,00" Grados_F.Text = "32,00"End Sub---------------------------------------------------------------------------Private Sub Fahrenheit_Click() Dim GradosFahr As Double GradosFahr = Grados_C.Text * 9 / 5 + 32 Grados_F.Text = Format(GradosFahr, "#,##0.00")End Sub---------------------------------------------------------------------------Private Sub Centígrados_Click() Dim GradosCent As Double GradosCent = (Grados_F.Text - 32) * 5 / 9 Grados_C.Text = Format(GradosCent, "#,##0.00")End Sub---------------------------------------------------------------------------Private Sub Grados_C_Change()End Sub---------------------------------------------------------------------------Private Sub Grados_F_Change()End Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub

Page 5: Talleres Visual Basic Basico 2[1]

3.Tercer Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Picturebox1 Nombre = Picture1Form Autoredraw = True

Option ExplicitDim NomAp As String, Edad As Integer, FechaNa As Date---------------------------------------------------------------------------Private Sub Form_Load() 'Entrada de datos NomAp = InputBox("Nombre y apellidos:", , "Nombre Apellidos") Edad = InputBox("Edad:", , 1) FechaNa = InputBox("Fecha:", , #1/1/1980#) 'Salida de datos Picture1.Print NomAp Picture1.Print Edad Picture1.Print FechaNaEnd Sub---------------------------------------------------------------------------Private Sub Picture1_Click()End Sub---------------------------------------------------------------------------

Page 6: Talleres Visual Basic Basico 2[1]

4. Cuarto Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load() Form1.Caption = "Saludo" Form1.AutoRedraw = True Form1.Print "Bienvenido a Visual Basic"End Sub---------------------------------------------------------------------------

Page 7: Talleres Visual Basic Basico 2[1]

5. Quito Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Texbox1 Nombre = mensajeCommandbotton1 Nnombre = orden1Form Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load()End Sub---------------------------------------------------------------------------Private Sub Mensaje_Change() Orden1.Caption = "Restaurar Msg"End Sub---------------------------------------------------------------------------Private Sub Orden1_Click() Mensaje.Text = "Bienvenido a Visual Basic" Orden1.Caption = "Haga clic aquí"End Sub---------------------------------------------------------------------------

Page 8: Talleres Visual Basic Basico 2[1]

6.Sexto Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = Conversiones Numericas Autoredraw = TrueModulo1

Ojo Esto en la forma:

Option ExplicitPublic varform As Integer---------------------------------------------------------------------------Private Sub Form_Load() ent1 = 40.17 ent2 = 37.83 Print ent1, ent2 'resultado: 40 38 fracsp = 22.3445577 ent2 = 17.5 Print fracsp, ent2 'resultado: 22.34456 18 fracsp = 17.55 fracdp = fracsp Print fracsp, fracdp 'resultado: 17.55 17.5499992370605 ent1 = 8 fracdp = 3 Print ent1 / fracdp 'resultado: 2.66666666666667 Test 'llama al procedimiento Test del módulo estándarEnd Sub---------------------------------------------------------------------------

Ojo Esto en el Modulo

Option Explicit

Public ent1 As Integer, ent2 As IntegerPublic fracsp As Single, fracdp As Double---------------------------------------------------------------------------Public Sub Test()

Page 9: Talleres Visual Basic Basico 2[1]

'varform está definida en el formulario Form1.varform = 10 Form1.Print Form1.varformEnd Sub---------------------------------------------------------------------------

Page 10: Talleres Visual Basic Basico 2[1]

7.Septimo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load() 'Interés compuesto Dim Capital As Double, TpInt As Integer Dim nAños As Integer, r As Integer, I As Integer

Capital = InputBox("Capital a invertir") nAños = InputBox("Periodo en años") r = InputBox("Tipo de interés") 'Escribir año a año los resultados redondeados For I = 1 To nAños Capital = Int(Capital + r / 100 * Capital + 0.5) Print "Capital total después de"; I; "años"; Capital Next IEnd Sub---------------------------------------------------------------------------

Page 11: Talleres Visual Basic Basico 2[1]

8.Octavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load() 'Indicar los días correspondientes a un mes de un año dado Dim mes As Integer, año As Integer, días As Integer

mes = InputBox("Introducir el mes (##):") año = InputBox("Introducir el año (####):") Select Case mes Case 1, 3, 5, 7, 8, 10, 12 'meses de 31 días días = 31 Case 4, 6, 9, 11 'meses de 30 días días = 30 Case 2 'Febrero If (año Mod 4 = 0) And (año Mod 100 <> 0) Or _ (año Mod 400 = 0) Then días = 29 'año bisiesto Else días = 28 'año bisiesto End If Case Else Print "El mes no es válido" días = 0 End Select If días <> 0 Then Print "El mes"; mes; "del año"; año; "tiene"; días; "días" End IfEnd Sub---------------------------------------------------------------------------

Page 12: Talleres Visual Basic Basico 2[1]

9.Noveno Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option Explicit

Private Sub Form_Load() 'Números impares Dim a As Integer, b As Integer Dim x As Integer, n As Integer a = InputBox("Extremo inferior del intervalo:") b = InputBox("Extremo superior del intervalo:") 'Verificar si a es menor que b If a > b Then Print "a no puede ser mayor que b. Los invertimos." x = a: a = b: b = x End If 'Localizar el primer número impar If a Mod 2 = 0 Then a = a + 1 'Escribir todos los números impares For n = a To b Step 2 Print n, Next nEnd Sub

Page 13: Talleres Visual Basic Basico 2[1]

10.Decimo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option ExplicitPrivate Type Ficha nombre As String * 40 nota As SingleEnd TypePrivate alumno() As Ficha---------------------------------------------------------------------------Private Sub Form_Load() Dim n As Integer, i As Integer Dim s As Integer, k As Integer Dim aux As Ficha

n = InputBox("Número de alumnos de la lista") ReDim alumno(1 To n) 'Lista de estructuras

'Entrada de datos For i = 1 To n alumno(i).nombre = InputBox("Nombre:") alumno(i).nota = InputBox("Nota:") Next i

'Ordenación de los elementos de la lista s = 1 'indicador de si la lista está o no ordenada k = n 'total elementos de la lista While (s = 1) And (k > 1) s = 0 'suponemos que la lista está ordenada For i = 2 To k '¿el nombre (i-1) está por orden alfabético después que el (i)? If alumno(i - 1).nombre > alumno(i).nombre Then 'Permutar las estructuras aux = alumno(i - 1) alumno(i - 1) = alumno(i) alumno(i) = aux s = 1 'la lista no estaba ordenada End If Next i k = k - 1 Wend

Page 14: Talleres Visual Basic Basico 2[1]

'Escribir la lista For i = 1 To n Print alumno(i).nombre; Tab(40); alumno(i).nota Next iEnd Sub---------------------------------------------------------------------------

Page 15: Talleres Visual Basic Basico 2[1]

11.Decimo Primer Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load() 'Creación de una matriz unidimensional Const N = 12 Dim a(N) As Double, i As Integer

'Entrada de datos For i = 0 To N a(i) = InputBox("Valor numérico para a(" & i & ")") Next i

'Salida de datos For i = 0 To N Print a(i); Next i Print 'Mueve el cursor a la línea siguiente Print "Fin del proceso"End Sub---------------------------------------------------------------------------

Page 16: Talleres Visual Basic Basico 2[1]

12.Decimo Segundo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Label1 Caption = ElementoLabel2 Caption = ValorTextBox1 Nombre = IndiceTextBox2 Nombre = ValorElementoTextBox3 Nombre = DatosMatizCommandbotton1 Nombre = IndIndiceCommandbotton1 Nombre = DecIndiceCommandbotton1 Nombre = AceptarCommandbotton1 Nombre = VisualizarMatrizForm Autoredraw = True

Option ExplicitConst N = 20Private a(N) As Double---------------------------------------------------------------------------Private Sub Aceptar_Click() a(Indice.Text) = ValorElemento.Text IncIndice.Value = TrueEnd Sub---------------------------------------------------------------------------Private Sub DatosMatriz_Change()End Sub---------------------------------------------------------------------------Private Sub DecIndice_Click() Dim i As Integer i = Indice.Text If i = 0 Then Exit Sub Indice.Text = i - 1End Sub---------------------------------------------------------------------------Private Sub Form_Load() Indice.Text = 0 ValorElemento.Text = 0End Sub---------------------------------------------------------------------------Private Sub IncIndice_Click() Dim i As Integer i = Indice.Text If i = N Then Exit Sub Indice.Text = i + 1End Sub---------------------------------------------------------------------------Private Sub Indice_KeyPress(KeyAscii As Integer)

Page 17: Talleres Visual Basic Basico 2[1]

Dim car As String * 1 'cadena de un sólo carácter car = Chr(KeyAscii) 'carácter tecleado If InStr("+-0123456789," & Chr(8), car) = 0 Then KeyAscii = 0 'eliminar el carácter tecleado Beep 'señal acústica End IfEnd Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub ValorElemento_KeyPress(KeyAscii As Integer) Dim car As String * 1 'cadena de un sólo carácter car = Chr(KeyAscii) 'carácter tecleado If InStr("+-0123456789," & Chr(8), car) = 0 Then KeyAscii = 0 'eliminar el carácter tecleado Beep 'señal acústica End IfEnd Sub---------------------------------------------------------------------------Private Sub VisualizarMatriz_Click() Dim i As Integer 'Borrar el contenido de la caja de texto multilínea DatosMatriz.Text = "" 'Visualizar en la caja de texto todos los elementos de la matriz For i = 0 To N DatosMatriz.SelStart = Len(DatosMatriz) 'situarse al final 'Añadir el siguiente elemento a la caja de texto DatosMatriz.SelText = "a(" & i & ") = " & a(i) & vbCrLf Next iEnd Sub---------------------------------------------------------------------------

Page 18: Talleres Visual Basic Basico 2[1]

13.Decimo Tercer Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option ExplicitDim m() As IntegerDim x() As Integer---------------------------------------------------------------------------Private Sub Form_Load() 'Crear una matriz bidimensional Dim nf As Integer, nc As Integer 'número de filas y de columnas Dim f As Integer, c As Integer 'fila y columna actuales Dim sumafila As Integer 'suma de cada fila nf = InputBox("Número de filas de la matriz:") nc = InputBox("Número de columnas de la matriz:") ReDim m(1 To nf, 1 To nc) ReDim x(1 To nf, 1 To nc)

'Entrada de datos For f = 1 To nf For c = 1 To nc m(f, c) = InputBox("m(" & f & ", " & c & ") = ") Next c Next f 'Copiar la matriz m en la matriz x For f = 1 To nf For c = 1 To nc x(f, c) = m(f, c) Next c Next f 'Escribir la suma de cada fila For f = 1 To nf sumafila = 0 For c = 1 To nc sumafila = sumafila + x(f, c) Next c Print "Suma de la fila"; f; " = "; sumafila Next fEnd Sub

Page 19: Talleres Visual Basic Basico 2[1]

14.Decimo Cuarto Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option ExplicitPrivate notas() As Single---------------------------------------------------------------------------Private Sub Form_Load() 'Nota media del curso Dim nalumnos As Integer 'número de alumnos Dim i As Integer 'índice Dim suma As Single 'suma total de todas las notas nalumnos = InputBox("Número de alumnos:") ReDim notas(1 To nalumnos) 'Entrada de datos For i = 1 To nalumnos notas(i) = InputBox("Alumno " & i & ", nota final:") Next i

'Sumar las notas For i = 1 To nalumnos suma = suma + notas(i) Next i 'Escribir resultados Print "La nota media del curso es "; _ Format(suma / nalumnos, "#0.00")

'Nota máxima y mínima Dim max As Single, min As Single max = notas(1): min = notas(1) For i = 2 To nalumnos If notas(i) > max Then max = notas(i) If notas(i) < min Then min = notas(i) Next i Print "La nota máxima: "; Format(max, "#0.00") Print "La nota mínima: "; Format(min, "#0.00")End Sub

Page 20: Talleres Visual Basic Basico 2[1]

15.Decimo Quinto Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option Explicit

Private Type Ficha nombre As String * 40 nota As SingleEnd TypePrivate alumno() As Ficha---------------------------------------------------------------------------Private Sub Form_Load() Dim n As Integer, i As Integer Dim s As Integer, k As Integer Dim aux As Ficha

n = InputBox("Número de alumnos de la lista") ReDim alumno(1 To n) As Ficha 'Lista de estructuras

'Entrada de datos For i = 1 To n alumno(i).nombre = InputBox("Nombre:") alumno(i).nota = InputBox("Nota:") Next i

'Ordenación de los elementos de la lista s = 1 'indicador de si la lista está o no ordenada k = n 'total elementos de la lista While (s = 1) And (k > 1) s = 0 'suponemos que la lista está ordenada For i = 2 To k '¿el nombre (i-1) está por orden alfabético después que el (i)? If alumno(i - 1).nombre > alumno(i).nombre Then 'Permutar las estructuras aux = alumno(i - 1) alumno(i - 1) = alumno(i) alumno(i) = aux s = 1 'la lista no estaba ordenada End If Next i k = k - 1 Wend

Page 21: Talleres Visual Basic Basico 2[1]

'Escribir la lista For i = 1 To n Print alumno(i).nombre; Tab(40); alumno(i).nota Next iEnd Sub---------------------------------------------------------------------------

Page 22: Talleres Visual Basic Basico 2[1]

16.Decimo Sexto Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = Dado Autoredraw = TrueLabel3 Caption = NumeroTextBox1 Nombre = DadoCommandbotton1 Nombre = TiradaCommandbotton1 Nombre = fin

Option ExplicitPrivate límitesup As Integer, límiteinf As Integer---------------------------------------------------------------------------Private Sub Dado_Click()End Sub---------------------------------------------------------------------------Private Sub Fin_Click() EndEnd Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub Tirada_Click() Dado.Caption = Str(Int((límitesup - límiteinf + 1) * Rnd + límiteinf))End Sub---------------------------------------------------------------------------Private Sub Form_Load() 'Tirada de un dado límitesup = 6 límiteinf = 1 Randomize 'iniciar generadorEnd Sub---------------------------------------------------------------------------Private Sub tirada_KeyPress(KeyAscii As Integer) Tirada.Value = True 'invoca al procedimiento Tirada_ClickEnd Sub

Page 23: Talleres Visual Basic Basico 2[1]

17.Decimo Septimo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = funcion Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load() Dim a(1 To 3) As Single, Media As Single 'Asignar valores a la matriz a a(1) = 3: a(2) = 5: a(3) = 8 Media = fnMedia(a) 'se pasa como argumento la matriz a Print Media procSuma a, 3 'se pasa como argumento la matriz a y su 'número de elementos. También se podría 'escribir: Call procSuma(a, 3)End Sub---------------------------------------------------------------------------

Ojo Esto en el Modulo

Option Explicit---------------------------------------------------------------------------Public Function fnMedia(x() As Single) As Single Dim v, Suma As Single, n As Integer 'Calcular la media de los valores de la matriz x For Each v In x Suma = Suma + v 'acumulador n = n + 1 'contador Next fnMedia = Suma / n 'valor que se devuelveEnd Function---------------------------------------------------------------------------Public Sub procSuma(x() As Single, n As Integer) Dim i, Suma As Single 'Calcular la suma de los valores de la matriz x For i = 1 To n Suma = Suma + x(i) 'acumulador Next i Form1.Print SumaEnd Sub

Page 24: Talleres Visual Basic Basico 2[1]

18.Decimo Octavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = funcionar Autoredraw = True

Option Explicit---------------------------------------------------------------------------Const dimA = 12, dimN = 8, dimF = 20Private ListaActual() As String, ListaNueva() As StringPrivate ListaFinal() As String---------------------------------------------------------------------------Private Sub Form_Load() Dim ind As Integer 'Fusionar dos listas clasificadas ReDim ListaActual(1 To dimA), ListaNueva(1 To dimN), _ ListaFinal(1 To dimF) 'Entrada de datos. 'Inicializamos las listas a clasificar con el fin de no tener 'que leer los datos y realizar así una prueba rápida. ListaActual(1) = "Ana": ListaActual(2) = "Carmen" ListaActual(3) = "David": ListaActual(4) = "Francisco" ListaActual(5) = "Javier": ListaActual(6) = "Jesús" ListaActual(7) = "José": ListaActual(8) = "Josefina" ListaActual(9) = "Luis": ListaActual(10) = "María" ListaActual(11) = "Patricia": ListaActual(12) = "Sonia" ListaNueva(1) = "Agustín": ListaNueva(2) = "Belén" ListaNueva(3) = "Daniel": ListaNueva(4) = "Fernando" ListaNueva(5) = "Manuel": ListaNueva(6) = "Pedro" ListaNueva(7) = "Rosa": ListaNueva(8) = "Susana" 'Datos para la lista actual 'For ind = 1 To dimA ' ListaActual(ind) = InputBox("Lista actual, " & ind & ":") 'Next ind 'Datos para la lista nueva 'For ind = 1 To dimN ' ListaNueva(ind) = InputBox("Lista nueva, " & ind & ":") 'Next ind 'Llamar al procedimiento Fusionar Fusionar ListaActual, dimA, _ ListaNueva, dimN, _

Page 25: Talleres Visual Basic Basico 2[1]

ListaFinal, dimF

'Escribir resultados For ind = 1 To dimF Print ListaFinal(ind) ' Lista resultante Next indEnd Sub

Ojo Esto en el Modulo

Option Explicit---------------------------------------------------------------------------Sub Fusionar(ListaA() As String, dimA As Integer, _ ListaN() As String, dimN As Integer, _ ListaF() As String, dimF As Integer) 'Procedimiento para fusionar dos listas clasificadas Dim ind As Integer, indA As Integer Dim indN As Integer, indF As Integer If (dimA + dimN = 0) Or (dimA + dimN > dimF) Then Form1.Print "Longitud insuficiente de la lista final" Exit Sub End If 'Fusionar indA = 1: indN = 1: indF = 1 Do While (indA <= dimA) And (indN <= dimN) If ListaA(indA) < ListaN(indN) Then ListaF(indF) = ListaA(indA) indA = indA + 1 Else ListaF(indF) = ListaN(indN) indN = indN + 1 End If indF = indF + 1 Loop

'Los dos lazos siguientes son para prever el caso de que, 'lógicamente, una lista finalice antes que la otra. For ind = indA To dimA ListaF(indF) = ListaA(ind) indF = indF + 1 Next ind For ind = indN To dimN ListaF(indF) = ListaN(ind) indF = indF + 1 Next indEnd Sub

Page 26: Talleres Visual Basic Basico 2[1]

19.Decimo Noveno Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = Calculadora Autoredraw = TrueTextBox1 Nombre = Pantalla Backcolor = AmarilloCommandbotton(0) Caption = 0 Nombre = DigitoCommandbotton(1) Caption = 1 Nombre = DigitoCommandbotton(2) Caption = 2 Nombre = DigitoCommandbotton(3) Caption = 3 Nombre = DigitoCommandbotton(4) Caption = 4 Nombre = DigitoCommandbotton(5) Caption = 5 Nombre = DigitoCommandbotton(6) Caption = 6 Nombre = DigitoCommandbotton(7) Caption = 7 Nombre = DigitoCommandbotton(8) Caption = 8 Nombre = DigitoCommandbotton(9) Caption = 9 Nombre = DigitoCommandbotton 1 Caption = . Nombre = PuntoDCommandbotton 2 Caption = C Nombre = IniciarCommandbotton 3 Caption = CE Nombre = BorrarEntradaCommandbotton(0) Caption = 0 Nombre = DigitoCommandbotton(4) Caption = - Nombre = OperacionCommandbotton(3) Caption = / Nombre = OperaconCommandbotton(2) Caption = + Nombre = OperaconCommandbotton(1) Caption = X Nombre = OperaconCommandbotton(0) Caption = = Nombre = OperaconCommandbotton 4 Caption = % Nombre = TantopoCiento

Private Enum CtesCalculadora NINGUNA DÍGITO_ OPERADOR_ CEEnd EnumPrivate UltimaEntrada As CtesCalculadoraPrivate PuntoDecimal As BooleanPrivate NumOperandos As IntegerPrivate Operando1 As Double, Operando2 As DoublePrivate Operador As String * 1---------------------------------------------------------------------------Private Sub BorrarEntrada_Click()

Page 27: Talleres Visual Basic Basico 2[1]

Pantalla.Caption = "0." PuntoDecimal = False UltimaEntrada = CEEnd Sub---------------------------------------------------------------------------Private Sub Dígito_Click(Index As Integer) Dim Número As String If UltimaEntrada <> DÍGITO_ Then If Dígito(Index).Caption = "0" Then Exit Sub Pantalla.Caption = "" PuntoDecimal = False UltimaEntrada = DÍGITO_ End If Número = Pantalla.Caption Pantalla.Caption = Número & Dígito(Index).CaptionEnd Sub---------------------------------------------------------------------------Private Sub Form_Load() NumOperandos = 0 Operando1 = 0 Operando2 = 0 UltimaEntrada = NINGUNA Operador = "" PuntoDecimal = FalseEnd Sub---------------------------------------------------------------------------Private Sub Iniciar_Click() Pantalla.Caption = "0." Form_LoadEnd Sub---------------------------------------------------------------------------Private Sub Operación_Click(Index As Integer) If NumOperandos = 0 And Operación(Index).Caption = "-" Then UltimaEntrada = DÍGITO_ End If If UltimaEntrada = DÍGITO_ Then NumOperandos = NumOperandos + 1 End If If NumOperandos = 1 Then Operando1 = Val(Pantalla.Caption) ElseIf NumOperandos = 2 Then Operando2 = Val(Pantalla.Caption) Select Case Operador Case "+": Operando1 = Operando1 + Operando2 Case "-": Operando1 = Operando1 - Operando2 Case "X": Operando1 = Operando1 * Operando2 Case "/": Operando1 = Operando1 / Operando2 Case "=": Operando1 = Operando2 End Select Pantalla.Caption = Str(Operando1) NumOperandos = 1 End If UltimaEntrada = OPERADOR_ Operador = Operación(Index).CaptionEnd Sub

Page 28: Talleres Visual Basic Basico 2[1]

---------------------------------------------------------------------------Private Sub Pantalla_Click()End Sub---------------------------------------------------------------------------Private Sub PuntoD_Click() If UltimaEntrada <> DÍGITO_ Then Pantalla.Caption = "0." ElseIf Not PuntoDecimal Then Pantalla.Caption = Pantalla.Caption & "." End If PuntoDecimal = True UltimaEntrada = DÍGITO_End Sub---------------------------------------------------------------------------Private Sub TantoPorCiento_Click() Dim Resultado As Double If UltimaEntrada = DÍGITO_ Then Resultado = Operando1 * Val(Pantalla.Caption) / 100 Pantalla.Caption = Str(Resultado) Operación_Click (0) 'para "=", Index es 0 UltimaEntrada = OPERADOR_ End IfEnd Sub

Page 29: Talleres Visual Basic Basico 2[1]

20.Veinte Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = TantoPorCiento Autoredraw = TrueLabel1 Caption = CantidadLabel2 Caption = %Label3 Caption = TotalTextBox1 Caption = Backcolor = AmarilloTextBox2 Caption = Backcolor = AmarilloTextBox3 Caption = Backcolor = AmarilloCommandbotton(0) Caption = 7 % Nombre = TantoPorCientoCommandbotton(1) Caption = 16 % Nombre = TantoPorCientoCommandbotton(2) Caption = 33 % Nombre = TantoPorCiento

Option ExplicitPrivate CantIni As Double---------------------------------------------------------------------------Private Sub Form_Load()End Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub TantoPorCiento_Click(Index As Integer) Dim T As Double, Tp As Double Tp = Val(TantoPorCiento(Index).Caption) CantIni = Text1.Text T = Tp / 100 * CantIni Label2.Caption = Tp & "%:" Text2.Text = Format(T, "#,###,###,##0") Text3.Text = Format(CantIni + T, "#,###,###,##0")End Sub---------------------------------------------------------------------------Private Sub Text1_Change() Static Botón54 As Boolean CantIni = Text1.Text If CantIni >= 100000000 And Not Botón54 Then

Page 30: Talleres Visual Basic Basico 2[1]

Load TantoPorCiento(3) TantoPorCiento(3).Left = 960 TantoPorCiento(3).Top = 1440 TantoPorCiento(3).Caption = "54%" TantoPorCiento(3).Visible = True Botón54 = True ElseIf CantIni < 100000000 And Botón54 Then Unload TantoPorCiento(3) Botón54 = False End IfEnd Sub---------------------------------------------------------------------------Private Sub Text2_Change()End Sub---------------------------------------------------------------------------Private Sub Text3_Change()End Sub

Page 31: Talleres Visual Basic Basico 2[1]

21. Veintiunavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Editor Autoredraw = TrueTextBox1 Caption = Ingresar al menu de Herramientas y seleccionar Editor de Menus donde aparece el siguiente menú

Para poder realizar alguna operación sobre esta interfece debe pararce en Caption $Fichero, Name: MenuFichero y luego el boton Siguiente, y asi para los siguientes botones

Luego de generar los menú la interface quedara de la siguiente manera:

Option ExplicitPrivate IndFuente As IntegerPrivate IndTamaño As Integer---------------------------------------------------------------------------Private Sub AyudaAcercaDe_Click() AcercaDe.Show vbModal, Me 'caja de diálogo modalEnd Sub

Page 32: Talleres Visual Basic Basico 2[1]

---------------------------------------------------------------------------Private Sub ColorFondo_Click(Index As Integer) Select Case Index Case 0 'color de fondo blanco Text1.BackColor = RGB(255, 255, 255) Case 1 'color de fondo verde Text1.BackColor = RGB(0, 255, 0) Case 2 'color de fondo azul Text1.BackColor = RGB(0, 0, 255) End SelectEnd Sub---------------------------------------------------------------------------Private Sub ColorTexto_Click(Index As Integer) Select Case Index Case 0 'color de fondo negro Text1.ForeColor = RGB(0, 0, 0) Case 1 'color de fondo verde Text1.ForeColor = RGB(0, 255, 0) Case 2 'color de fondo azul Text1.ForeColor = RGB(0, 0, 255) End SelectEnd Sub---------------------------------------------------------------------------Private Sub EdiciónCopiar_Click() Clipboard.SetText Text1.SelTextEnd Sub---------------------------------------------------------------------------Private Sub EdiciónCortar_Click() Clipboard.SetText Text1.SelText Text1.SelText = ""End Sub---------------------------------------------------------------------------Private Sub EdiciónPegar_Click() Text1.SelText = Clipboard.GetText()End Sub---------------------------------------------------------------------------Private Sub FicheroSalir_Click() EndEnd Sub---------------------------------------------------------------------------Private Sub Form_Load() Clipboard.Clear 'Vaciar la portapapeles Text1.Font.Name = "Arial" 'Fuente por defecto, Arial IndFuente = 1 Text1.Font.Size = 10 'Tamaño por defecto 10 IndTamaño = 0End Sub---------------------------------------------------------------------------Private Sub Fuente_Click(Index As Integer) Fuente(IndFuente).Checked = False Text1.Font.Name = Fuente(Index).Caption Fuente(Index).Checked = True IndFuente = IndexEnd Sub---------------------------------------------------------------------------

Page 33: Talleres Visual Basic Basico 2[1]

Private Sub MenúAyuda_Click()End Sub---------------------------------------------------------------------------Private Sub MenúEdición_Click() 'Activar/desactivar Cortar y Copiar si hay/no hay 'texto seleccionado EdiciónCortar.Enabled = (Text1.SelLength > 0) EdiciónCopiar.Enabled = (Text1.SelLength > 0) 'Activar/desactivar Pegar si hay/no hay texto en el portapapeles EdiciónPegar.Enabled = (Len(Clipboard.GetText()) > 0)End Sub---------------------------------------------------------------------------Private Sub MenúFichero_Click()End Sub---------------------------------------------------------------------------Private Sub MenúOpciones_Click()End Sub---------------------------------------------------------------------------Private Sub OpcionesColores_Click()End Sub---------------------------------------------------------------------------Private Sub OpcionesTexto_Click()End Sub---------------------------------------------------------------------------Private Sub Tamaño_Click(Index As Integer) Tamaño(IndTamaño).Checked = False Text1.Font.Size = Tamaño(Index).Caption Tamaño(Index).Checked = True IndTamaño = IndexEnd Sub

Page 34: Talleres Visual Basic Basico 2[1]

22. Veintidosavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Editor Autoredraw = TrueLabel1 Caption = HoraLabel2 Caption = DespertadorLabel 3 Caption= nombre = horaTextBox1 Caption = DespertadorTimer

Ingresar al menu de Herramientas y seleccionar Editor de Menus donde aparece el siguiente menú

Para poder realizar alguna operación sobre esta interfece debe pararce en Caption $despertador, Name: MenuDespertador y luego el boton Siguiente, y asi para los siguientes botones

Luego de generar los menú la interface quedara de la siguiente manera:

Private DespertadorSi As Boolean---------------------------------------------------------------------------Private Sub Cerrar_Click() EndEnd Sub---------------------------------------------------------------------------Private Sub Despertador_KeyPress(KeyAscii As Integer) Dim Car As String * 1

Page 35: Talleres Visual Basic Basico 2[1]

Car = Chr(KeyAscii) If (Car < "0" Or Car > "9") And Car <> ":" Then Beep 'aviso acústico KeyAscii = 0 'borrar carácter End IfEnd Sub---------------------------------------------------------------------------Private Sub DespertadorSiNo_Click() If (DespertadorSi) Then DespertadorSi = False DespertadorSiNo.Caption = "Despertador No" Else DespertadorSi = True DespertadorSiNo.Caption = "Despertador Sí" End IfEnd Sub---------------------------------------------------------------------------Private Sub Form_Load() DespertadorSi = False Despertador.Text = "00:00:00"End Sub---------------------------------------------------------------------------Private Sub Hora_Click()End Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub MenúDespertador_Click()End Sub---------------------------------------------------------------------------Private Sub Timer1_Timer() If (Despertador.Text < CStr(Time) And DespertadorSi) ThenBeep: Beep: Beep End If Hora.Caption = TimeEnd Sub

Page 36: Talleres Visual Basic Basico 2[1]

23. Veintitresavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Ansi Autoredraw = TrueLabel1 Caption = Codigo AsciLabel2 Caption = CaracterLabel Nombre = CodigoLabel Nombre = CarácterHscrolbar Nombre = Desh

Option Explicit---------------------------------------------------------------------------Private Sub Carácter_Click()End Sub---------------------------------------------------------------------------Private Sub Código_Click()End Sub---------------------------------------------------------------------------Private Sub DesH_Change() Código.Caption = Format(DesH.Value) Carácter.Caption = Chr(DesH.Value)End Sub---------------------------------------------------------------------------Private Sub DesH_Scroll() Código.Caption = Format(DesH.Value) Carácter.Caption = Chr(DesH.Value)End Sub---------------------------------------------------------------------------Private Sub Form_Load()End Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub

Page 37: Talleres Visual Basic Basico 2[1]

24. VeintiCuatroavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Botones de opciones Autoredraw = TrueOptionBotton nombre = DecimalOptionBotton nombre = OctalOptionBotton nombre = HexadecimalTextbos1 text = en blanco

Option ExplicitPrivate NúmeroActual As LongPrivate Deci As String * 14Private Octa As String * 10Private Hexa As String * 18Private Car As String * 1, vr As Integer, Texto As StringConst MáxEnt = 2147483647---------------------------------------------------------------------------Private Sub Form_Load() Deci = "+-0123456789" & vbBack Octa = "01234567" & vbBack Hexa = "0123456789ABCDEF" & vbBackEnd Sub---------------------------------------------------------------------------Private Sub Decimal_Click() Text1.Text = Format(NúmeroActual) Text1.SetFocusEnd Sub---------------------------------------------------------------------------Private Sub Octal_Click() Text1.Text = Oct(NúmeroActual) Text1.SetFocusEnd Sub---------------------------------------------------------------------------Private Sub Hexadecimal_Click() Text1.Text = Hex(NúmeroActual) Text1.SetFocusEnd Sub---------------------------------------------------------------------------Private Sub Text1_Change() Texto = LTrim(Text1.Text) If Octal.Value Then Texto = "&O" & Texto ElseIf Hexadecimal.Value Then Texto = "&H" & Texto End If If Val(Texto) < (-MáxEnt - 1) Or _ Val(Texto) > MáxEnt Then

Page 38: Talleres Visual Basic Basico 2[1]

MsgBox "Valor fuera de los límites", vbCritical Else NúmeroActual = Val(Texto) End IfEnd Sub---------------------------------------------------------------------------Private Sub Text1_KeyPress(keyAscii As Integer) Car = UCase(Chr(keyAscii)) If Decimal.Value Then vr = InStr(Deci, Car) ElseIf Octal.Value Then vr = InStr(Octa, Car) ElseIf Hexadecimal.Value Then vr = InStr(Hexa, Car) End If If vr = 0 Then Beep keyAscii = 0 End IfEnd Sub

Page 39: Talleres Visual Basic Basico 2[1]

25. VeintiCincoavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = marcos y Opciones Autoredraw = TrueFrame1 Caption = BaseOptionBotton Caption = Decimal Nombre =BaseOptionBotton Caption = Octal Nombre =BaseOptionBotton Caption = Hexadecimal Nombre =BaseFrame2 Caption = LongitudOptionBotton Caption = 16 Bist Nombre =longitudOptionBotton Caption = 32 Bist Nombre =longitudeTextbos1 text = en Banco

Option ExplicitPrivate NúmeroActual As VariantPrivate Deci As String * 14Private Octa As String * 10Private Hexa As String * 18Private Car As String * 1, vr As Integer, Texto As StringPrivate MáxEnt As Variant---------------------------------------------------------------------------Private Sub Form_Load() Deci = "+-0123456789" & vbBack Octa = "01234567" & vbBack Hexa = "0123456789ABCDEF" & vbBack MáxEnt = 2147483647 ' valor por defectoEnd Sub---------------------------------------------------------------------------Private Sub Frame1_DragDrop(Source As Control, X As Single, Y As Single)End Sub---------------------------------------------------------------------------Private Sub Frame2_DragDrop(Source As Control, X As Single, Y As Single)End Sub---------------------------------------------------------------------------Private Sub Text1_KeyPress(keyAscii As Integer) Car = UCase(Chr(keyAscii)) If Base(0).Value Then ' decimal vr = InStr(Deci, Car) ElseIf Base(1).Value Then ' octal vr = InStr(Octa, Car) ElseIf Base(2).Value Then ' hexadecimal vr = InStr(Hexa, Car) End If If vr = 0 Then Beep

Page 40: Talleres Visual Basic Basico 2[1]

keyAscii = 0 End IfEnd Sub---------------------------------------------------------------------------Private Sub Text1_Change() Texto = LTrim(Text1.Text) If Base(1).Value Then ' octal Texto = "&O" & Texto ElseIf Base(2).Value Then ' hexadecimal Texto = "&H" & Texto End If If Val(Texto) < (-MáxEnt - 1) Or Val(Texto) > MáxEnt Then MsgBox "Valor fuera de los límites", vbCritical ElseIf Longitud(0).Value Then ' 16 bits NúmeroActual = CInt(Val(Texto)) ' Integer ElseIf Longitud(1).Value Then ' 32 bits NúmeroActual = CLng(Val(Texto)) ' Long End IfEnd Sub---------------------------------------------------------------------------Private Sub Base_Click(Index As Integer) If Index = 0 Then Text1.Text = Format(NúmeroActual) ElseIf Index = 1 Then Text1.Text = Oct(NúmeroActual) Else Text1.Text = Hex(NúmeroActual) End If Text1.SetFocusEnd Sub---------------------------------------------------------------------------Private Sub Longitud_Click(Index As Integer) If Index = 0 Then ' 16 bits MáxEnt = 32767 Else ' 32 bits MáxEnt = 2147483647 End If ActualizarEnd Sub---------------------------------------------------------------------------Private Sub Actualizar() ' Obtener el valor en el nº de bits elegido Text1_Change ' Actualizar Text1.Text al nº de bits elegido If Base(0).Value Then ' decimal Base_Click (0) ElseIf Base(1).Value Then ' octal Base_Click (1) ElseIf Base(2).Value Then ' hexadecimal Base_Click (2) End IfEnd Sub

Page 41: Talleres Visual Basic Basico 2[1]

26. VeintiSeisavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Caja de Dialogos Autoredraw = TrueTextbos1 text = en BancoCommand Dialog1

Ingresar al menu de Herramientas y seleccionar Editor de Menus donde aparece el siguiente menú

Para poder realizar alguna operación sobre esta interfece debe pararce en Caption $Fichero, Name: MenuFichero y luego el boton Siguiente, y asi para los siguientes botones

Luego de generar los menú la interface quedara de la siguiente manera:

Option Explicit---------------------------------------------------------------------------Private Sub FicheroAbrir_Click() Dim Filtros As String ' Si ocurre un error ejecutar ManipularErrorAbrir On Error GoTo ManipularErrorAbrir ' Generar un error cuando se pulse Cancelar CommonDialog1.CancelError = True ' Filtros Filtros = "Ficheros de proyecto (*.vbp)|*.vbp|" & _ "Imágenes(*.bmp;*.ico)|*.bmp;*.ico|" & _ "Todos los ficheros (*.*)|*.*" CommonDialog1.Filter = Filtros ' Filtro por defecto CommonDialog1.FilterIndex = 1 'ficheros de proyecto

Page 42: Talleres Visual Basic Basico 2[1]

' Visualizar la caja de diálogo CommonDialog1.ShowOpen ' CommonDialog1.FileTitle contiene el nombre ' del fichero elegido Text1.Text = CommonDialog1.FileTitle SalirAbrir: Exit Sub---------------------------------------------------------------------------ManipularErrorAbrir: ' Manipular el error If Err.Number = cdlCancel Then Exit Sub 'se pulsó Cancelar MsgBox Err.Description Resume SalirAbrirEnd Sub---------------------------------------------------------------------------Private Sub FicheroGuardar_Click() ' Si ocurre un error ejecutar ManipularErrorGuardar On Error GoTo ManipularErrorGuardar ' Generar un error cuando se pulse Cancelar CommonDialog1.CancelError = True ' Filtros CommonDialog1.Filter = "Ficheros de proyecto (*.vbp)|*.vbp|Todos los ficheros (*.*)|*.*" ' Filtro por defecto CommonDialog1.FilterIndex = 1 ' Visualizar la caja de diálogo CommonDialog1.ShowSave Text1.Text = CommonDialog1.FileTitle ' CommonDialog1.FileTitle contiene el nombre ' del fichero elegido SalirGuardar: Exit Sub---------------------------------------------------------------------------ManipularErrorGuardar: ' Manipular el error If Err.Number = cdlCancel Then Exit Sub MsgBox Err.Description Resume SalirGuardarEnd Sub---------------------------------------------------------------------------Private Sub FicheroImprimir_Click() ' Valores de impresión Dim PrimeraPag, ÚltimaPag, NumCopias, ImpArchivo, I ' Si ocurre un error ejecutar ManipularErrorImprimir On Error GoTo ManipularErrorImprimir ' Generar un error cuando se pulse Cancelar CommonDialog1.CancelError = True ' Visualizar la caja de diálogo CommonDialog1.ShowPrinter ' Obtener las propiedades de impresión PrimeraPag = CommonDialog1.FromPage ÚltimaPag = CommonDialog1.ToPage

Page 43: Talleres Visual Basic Basico 2[1]

NumCopias = CommonDialog1.Copies ImpArchivo = CommonDialog1.Flags And cdlPDPrintToFile ' Imprimir If ImpArchivo Then For I = 1 To NumCopias ' Escriba el código para enviar datos a un archivo Next I Else For I = 1 To NumCopias ' Printer.Print "Esta línea será enviada a la impresora" ' Escriba el código para enviar datos a la impresora Next I End If

SalirImprimir: Exit Sub---------------------------------------------------------------------------ManipularErrorImprimir: ' Manipular el error If Err.Number = cdlCancel Then Exit Sub MsgBox Err.Description Resume SalirImprimirEnd Sub---------------------------------------------------------------------------Private Sub FicheroSalir_Click() EndEnd Sub---------------------------------------------------------------------------Private Sub Form_Load()End Sub---------------------------------------------------------------------------Private Sub MenúFichero_Click()End Sub---------------------------------------------------------------------------Private Sub Separador1_Click()End Sub---------------------------------------------------------------------------Private Sub Separador2_Click()End Sub---------------------------------------------------------------------------Private Sub Text1_Change()End Sub

Page 44: Talleres Visual Basic Basico 2[1]

27. VeintiSieteavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Telefonos Autoredraw = TrueLabel1 Caption = NombreLabel2 Caption = DireccionLabel3 Caption = TelefonoLabel4 Caption = NotasTextbos1 text = en Banco Nombre = NombreTextbos2 text = en Banco Nombre = DireccionTextbos3 text = en Banco Nombre = TelefonoTextbos4 text = en Banco Nombre = NotasCommandButton1 Caption = Anadir Nombre = anadir

CommandButton2 Caption = Ver Nombre = VerCommandButton3 Caption = Borrar Nombre = BorrarCommandButton4 Caption = Salir Nombre = SalirComboBox Nombre = ListaTfnos

Option Explicit---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub Label4_Click()End Sub---------------------------------------------------------------------------Private Sub ListaTfnos_KeyPress(KeyAscii As Integer) Dim I As Integer For I = 0 To TotalRegs - 1 If Left(ListaTfnos.List(I), 1) = Str(KeyAscii) Then ListaTfnos.ListIndex = I Exit For End If Next IEnd Sub---------------------------------------------------------------------------Private Sub Nombre_GotFocus()

Page 45: Talleres Visual Basic Basico 2[1]

' Seleccionar el texto de la caja Nombre.SelStart = 0 Nombre.SelLength = Len(Nombre.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Dirección_GotFocus() ' Seleccionar el texto de la caja Dirección.SelStart = 0 Dirección.SelLength = Len(Dirección.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Teléfono_GotFocus() ' Seleccionar el texto de la caja Teléfono.SelStart = 0 Teléfono.SelLength = Len(Teléfono.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Notas_GotFocus() ' Seleccionar el texto de la caja Notas.SelStart = 0 Notas.SelLength = Len(Notas.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Añadir_Click() If Nombre.Text = "" Or Dirección.Text = "" Or Teléfono.Text = "" Then MsgBox "Complete los campos Dirección, Nombre y Teléfono" Exit Sub End If TotalRegs = TotalRegs + 1 Tfnos(TotalRegs).Nombre = Nombre.Text Tfnos(TotalRegs).Dirección = Dirección.Text Tfnos(TotalRegs).Teléfono = Teléfono.Text Tfnos(TotalRegs).Notas = Notas.Text 'Añadir el Nombre a la lista "ListaTfnos" ListaTfnos.AddItem Nombre.TextEnd Sub---------------------------------------------------------------------------Private Sub Ver_Click() Call VisualizarRegistro

Page 46: Talleres Visual Basic Basico 2[1]

End Sub---------------------------------------------------------------------------Private Sub ListaTfnos_DblClick() Call VisualizarRegistroEnd Sub---------------------------------------------------------------------------Private Sub Borrar_Click() Dim I As Integer, R As Integer 'Borrar el registro R de la matriz 'Comienza la búsqueda For I = 1 To TotalRegs If (RTrim(Tfnos(I).Nombre) = _ RTrim(ListaTfnos.Text)) Then Exit For End If Next I If I > TotalRegs Then Exit Sub 'no encontrado 'R = I es el registro a borrar. Se borra, retrocediendo una 'posición todos los registros que estén a continuación del 'registro R que queremos borrar For R = I To TotalRegs - 1 Tfnos(R) = Tfnos(R + 1) Next R 'Borrar los datos del último registro Tfnos(TotalRegs).Nombre = "" Tfnos(TotalRegs).Dirección = "" Tfnos(TotalRegs).Teléfono = "" Tfnos(TotalRegs).Notas = "" 'Actualizar el contador de registros TotalRegs = TotalRegs - 1 'Borrar el nombre que seleccionamos en la lista "ListaTfnos" 'Posición que ocupa el nombre en la lista R = ListaTfnos.ListIndex 'Borrar el nombre ListaTfnos.RemoveItem REnd Sub---------------------------------------------------------------------------Private Sub ListaTfnos_GotFocus() Ver.Enabled = True Borrar.Enabled = True Añadir.Enabled = FalseEnd Sub---------------------------------------------------------------------------Private Sub Form_Load() Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Salir_Click() Unload Form1 EndEnd Sub

Ojo Esto va en el modulo1

Page 47: Talleres Visual Basic Basico 2[1]

Option Explicit---------------------------------------------------------------------------Type Registro Nombre As String * 30 Dirección As String * 30 Teléfono As String * 12 Notas As String * 240End TypePublic Tfnos(1 To 99) As RegistroPublic TotalRegs As Integer---------------------------------------------------------------------------Public Sub VisualizarRegistro() Dim I As Integer, Encontrado As Boolean Encontrado = False 'elemento no encontrado For I = 1 To TotalRegs If (RTrim(Tfnos(I).Nombre) = _ RTrim(Form1.ListaTfnos.Text)) Then Encontrado = True 'elemento encontrado Exit For End If Next I If (Encontrado) Then Form1.Nombre.Text = RTrim(Tfnos(I).Nombre) Form1.Dirección.Text = RTrim(Tfnos(I).Dirección) Form1.Teléfono.Text = RTrim(Tfnos(I).Teléfono) Form1.Notas.Text = RTrim(Tfnos(I).Notas) Else MsgBox "El nombre especificado no se encuentra", 48, "Tfnos" End IfEnd Sub

Page 48: Talleres Visual Basic Basico 2[1]

28. VeintiOchoavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Casilla de verificacion Autoredraw = TrueTextbos1 text = en Banco Nombre = NombreCheckbox Caption = Convertir a mayusculas Nombre = ConverMayus

Option Explicit---------------------------------------------------------------------------Private Sub ConverMayus_Click() If ConverMayus.Value = 1 Then Text1.Text = UCase(Text1.Text) End If Text1.SetFocus Text1.SelStart = Len(Text1.Text)End Sub---------------------------------------------------------------------------Private Sub Form_Load()End Sub---------------------------------------------------------------------------Private Sub Text1_KeyPress(KeyAscii As Integer) Dim car As String * 1 If ConverMayus.Value = 1 Then car = UCase(Chr(KeyAscii)) KeyAscii = Asc(car) End IfEnd Sub

Page 49: Talleres Visual Basic Basico 2[1]

29. VeintiNoavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Autoredraw = TrueCommadBotton1 Caption = Demo Msgbox

Option Explicit---------------------------------------------------------------------------Private Sub Command1_Click() Dim Mensaje, Botones, Título, Respuesta Mensaje = "¿Desea continuar?" Botones = vbYesNo + vbQuestion + vbDefaultButton2 Título = "Eliminar fichero" Respuesta = MsgBox(Mensaje, Botones, Título)

If Respuesta = vbYes Then 'el usuario eligió el botón Sí. 'Ejecutar una acción Else 'el usuario eligió el botón No. 'Ejecutar otra acción End IfEnd Sub---------------------------------------------------------------------------Private Sub Form_Load()End Sub

Page 50: Talleres Visual Basic Basico 2[1]

30. Treintaavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Palabre de Paso Autoredraw = TrueLabel1 Caption = Introduzca laLabel2 Caption = palabre de pasoTextbox1 text = En blanco Nombre = Nombre

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load()End Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then If UCase(Text1.Text) <> "JAVIER" Then MsgBox "La palabra de paso no es correcta", vbCritical, _ "Palabra de paso" End Else MsgBox "Continúe", vbInformation, "Palabra de paso" Unload DlgPalPaso End If End IfEnd Sub

Page 51: Talleres Visual Basic Basico 2[1]

31. Treintaunavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Sistema de Fichero Autoredraw = TrueLabel1 Caption = Nombre del FicheroLabel Caption = directori: Nombre = NomDirLabel3 Caption = Unidad de disco Nombre = NomDirLabel4 Caption = Tipo de Fichero Nombre = NomDirTextbox1 text = En blanco Nombre = NomFicheroFileListBox Nombre = File 1ComboBox Nombre = TipoFicheroDriveListbox Nombre = Drive 1DirlistBox Nombre = Dir 1CommandButton1 Nombre = Aceptar Czption AceptarCommandButton2 Nombre = Cancelar Czption Cancelar

Option Explicit---------------------------------------------------------------------------Private Enum ConstantesSF NO_CLIC CLIC_EN_DIR CLIC_EN_FILEEnd EnumPrivate ÚltimoCambio As ConstantesSFPublic NomFichCompleto As String---------------------------------------------------------------------------Private Sub Form_Load() ' Inicializar la lista tipo de fichero TipoFichero.AddItem "Todos (*.*)" TipoFichero.AddItem "De texto (*.txt)" TipoFichero.AddItem "Documentos (*.doc)" ' Seleccionar el primer elemento de la lista para que sea el tipo ' de fichero por defecto TipoFichero.ListIndex = 0 'seleccionar el primer elemento ' Inicializar la etiqueta Directorio con el nombre del ' directorio actualmente seleccionado NomDir.Caption = Dir1.PathEnd Sub---------------------------------------------------------------------------Private Sub Drive1_Change() On Error GoTo DriverError

Page 52: Talleres Visual Basic Basico 2[1]

' Referir el camino a la nueva unidad Dir1.Path = Drive1.Drive Exit SubDriverError: MsgBox "Error: unidad no preparada", vbExclamation, "Error" Exit SubEnd Sub---------------------------------------------------------------------------Private Sub Dir1_Change() ' Actualizar la lista de ficheros File1.Path = Dir1.Path ' Actualizar la etiqueta Directorio NomDir.Caption = Dir1.PathEnd Sub---------------------------------------------------------------------------Private Sub Dir1_Click() ' Último clic en Dir1 ÚltimoCambio = CLIC_EN_DIREnd Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub Label4_Click()End Sub---------------------------------------------------------------------------Private Sub NomDir_Click()End Sub---------------------------------------------------------------------------Private Sub NomFichero_Change()End Sub---------------------------------------------------------------------------Private Sub TipoFichero_Click() ' Cambiar el patrón de la lista de ficheros de ' de acuerdo con el tipo de fichero seleccionado Select Case TipoFichero.ListIndex 'índice del elemento seleccionado Case 0 File1.Pattern = "*.*" Case 1 File1.Pattern = "*.txt" Case 2 File1.Pattern = "*.doc" End SelectEnd Sub---------------------------------------------------------------------------Private Sub File1_Click() ' Actualizar la caja de texto Nombre de fichero NomFichero.Text = File1.FileName ' Último clic en File1 ÚltimoCambio = CLIC_EN_FILEEnd Sub---------------------------------------------------------------------------

Page 53: Talleres Visual Basic Basico 2[1]

Private Sub File1_DblClick() ' Último clic en File1 ÚltimoCambio = CLIC_EN_FILE Aceptar_ClickEnd Sub---------------------------------------------------------------------------Private Sub Aceptar_Click() Aceptar.SetFocus 'enfocar el botón Aceptar On Error GoTo RutinaError Select Case ÚltimoCambio Case NO_CLIC ' se tecleó o no, un nombre de fichero NomFichCompleto = NomFichero.Text Case CLIC_EN_DIR Dir1.Path = Dir1.List(Dir1.ListIndex) Case CLIC_EN_FILE ' Obtener el camino completo del fichero ' Si el camino termina en \ If (Right(Dir1.Path, 1) = "\") Then NomFichCompleto = Dir1.Path & File1.FileName Else ' Si el camino no termina en \ NomFichCompleto = Dir1.Path & "\" & File1.FileName End If 'Si se sobreescribió el nombre de fichero If NomFichero.Text <> File1.FileName Then NomFichCompleto = NomFichero.Text End If End SelectSalir: ÚltimoCambio = NO_CLIC If NomFichCompleto <> "" Then SistemaDeFi.Hide Debug.Print NomFichCompleto End If Exit SubRutinaError: ' Manipular el error MsgBox Err.Description Resume SalirEnd Sub---------------------------------------------------------------------------Private Sub Cancelar_Click() SistemaDeFi.HideEnd Sub

Page 54: Talleres Visual Basic Basico 2[1]

32. Treintadosavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Editor de Menus Autoredraw = TrueCommamdDialog1 Nombre = CommonDialog1

Ingresar al menu de Herramientas y seleccionar Editor de Menus donde aparece el siguiente menú

Para poder realizar alguna operación sobre esta interfece debe pararce en Caption $Fichero, Name: MenuFichero y luego el boton Siguiente, y asi para los siguientes botones

Luego de generar los menú la interface quedara de la siguiente manera:

Option Explicit---------------------------------------------------------------------------Dim IndFuente As IntegerDim IndTamaño As Integer---------------------------------------------------------------------------Private Sub AyudaAcercaDe_Click() AcercaDe.Show vbModal, Me 'caja de diálogo modalEnd Sub---------------------------------------------------------------------------

Page 55: Talleres Visual Basic Basico 2[1]

Private Sub ColorFondo_Click(Index As Integer) Select Case Index Case 0 'color de fondo negro Text1.BackColor = RGB(0, 0, 0) Case 1 'color de fondo verde Text1.BackColor = RGB(0, 255, 0) Case 2 'color de fondo azul Text1.BackColor = RGB(0, 0, 255) End SelectEnd Sub---------------------------------------------------------------------------Private Sub ColorTexto_Click(Index As Integer) Select Case Index Case 0 'color de fondo blanco Text1.ForeColor = RGB(255, 255, 255) Case 1 'color de fondo verde Text1.ForeColor = RGB(0, 255, 0) Case 2 'color de fondo azul Text1.ForeColor = RGB(0, 0, 255) End SelectEnd Sub---------------------------------------------------------------------------Private Sub EdiciónCopiar_Click() Clipboard.SetText Text1.SelTextEnd Sub---------------------------------------------------------------------------Private Sub EdiciónCortar_Click() Clipboard.SetText Text1.SelText Text1.SelText = ""End Sub---------------------------------------------------------------------------Private Sub EdiciónPegar_Click() Text1.SelText = Clipboard.GetText()End Sub---------------------------------------------------------------------------Private Sub FicheroGuardar_Click() ' Si ocurre un error ejecutar ManipularErrorGuardar On Error GoTo ManipularErrorGuardar ' Filtros CommonDialog1.Filter = "Ficheros de texto (*.txt; *.doc)|" & _ "*.txt;*.doc|Todos los ficheros (*.*)|*.*" ' Filtro por defecto CommonDialog1.FilterIndex = 1 ' Visualizar la caja de diálogo CommonDialog1.ShowSave ' CommonDialog1.FileTitle contiene el nombre del ' fichero elegido. Escribir el texto en este fichero. Dim NumFichero As Integer ' Obtener un número libre de fichero NumFichero = FreeFile ' Abrir el fichero para escribir Open CommonDialog1.FileTitle For Output As NumFichero ' Guardar el texto en el fichero Print #NumFichero, Form1!Text1.Text

Page 56: Talleres Visual Basic Basico 2[1]

SalirGuardar: ' Cerrar el fichero Close NumFichero Exit Sub

ManipularErrorGuardar: ' Manipular el error MsgBox Err.Description Resume SalirGuardarEnd Sub---------------------------------------------------------------------------Private Sub FicheroAbrir_Click() ' Si ocurre un error ejecutar ManipularErrorAbrir On Error GoTo ManipularErrorAbrir ' Filtros CommonDialog1.Filter = "Ficheros de texto (*.txt; *.doc)|" & _ "*.txt;*.doc|Todos los ficheros (*.*)|*.*" ' Filtro por defecto CommonDialog1.FilterIndex = 1 ' Visualizar la caja de diálogo CommonDialog1.ShowOpen

' CommonDialog1.Filetitle contiene el nombre del ' fichero elegido. Leer el contenido de este fichero. Dim NumFichero As Integer ' Obtener un número libre de fichero NumFichero = FreeFile ' Abrir el fichero para leer Open CommonDialog1.FileTitle For Input As NumFichero ' Leer el texto del fichero Form1!Text1.Text = Input(LOF(1), #NumFichero)

SalirAbrir: ' Cerrar el fichero Close NumFichero Exit Sub

ManipularErrorAbrir: Dim Msg As String ' Manipular el error If Err.Number = 7 Then Msg = "El fichero es demasiado grande" ElseIf Err.Number = 53 Then Msg = "El fichero no existe" Else Msg = Err.Description End If MsgBox Msg, vbExclamation, "Editor" Resume SalirAbrirEnd Sub---------------------------------------------------------------------------Private Sub FicheroSalir_Click() EndEnd Sub

Page 57: Talleres Visual Basic Basico 2[1]

Private Sub Form_Load() Clipboard.Clear 'Borrar portapapeles Text1.FontName = "Arial" 'Fuente por defecto, Arial IndFuente = 1 Text1.FontSize = 10 'Tamaño por defecto 10 IndTamaño = 0 'Establecer como directorio de trabajo el directorio 'donde se ejcuta la aplicación ChDir App.PathEnd Sub---------------------------------------------------------------------------Private Sub Fuente_Click(Index As Integer) Fuente(IndFuente).Checked = False Text1.FontName = Fuente(Index).Caption Fuente(Index).Checked = True IndFuente = IndexEnd Sub---------------------------------------------------------------------------Private Sub MenúEdición_Click() 'Activar/desactivar Cortar y Copiar si hay/no hay 'texto seleccionado EdiciónCortar.Enabled = (Text1.SelLength > 0) EdiciónCopiar.Enabled = (Text1.SelLength > 0) 'Activar/desactivar Pegar si hay texto en el portapapeles EdiciónPegar.Enabled = (Len(Clipboard.GetText()) > 0)End Sub---------------------------------------------------------------------------Private Sub MenúFichero_Click()End Sub---------------------------------------------------------------------------Private Sub MenúOpciones_Click()End Sub---------------------------------------------------------------------------Private Sub OpcionesColores_Click()End Sub---------------------------------------------------------------------------Private Sub OpcionesTexto_Click()End Sub---------------------------------------------------------------------------Private Sub OpColorDelFondo_Click()End Sub---------------------------------------------------------------------------Private Sub OpColorDelTexto_Click()End Sub---------------------------------------------------------------------------Private Sub OpTextoFuentes_Click()End Sub---------------------------------------------------------------------------Private Sub OpTextoTamaño_Click()End Sub---------------------------------------------------------------------------Private Sub Separador_Click()End Sub---------------------------------------------------------------------------

Page 58: Talleres Visual Basic Basico 2[1]

Private Sub Tamaño_Click(Index As Integer) Tamaño(IndTamaño).Checked = False Text1.FontSize = Val(Tamaño(Index).Caption) Tamaño(Index).Checked = True IndTamaño = IndexEnd Sub---------------------------------------------------------------------------Private Sub Text1_Change()End Sub

Page 59: Talleres Visual Basic Basico 2[1]

33. VeintiTresavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Telefonos Autoredraw = TrueLabel1 Caption = NombreLabel2 Caption = DireccionLabel3 Caption = TelefonoLabel4 Caption = NotasTextbos1 text = en Banco Nombre = NombreTextbos2 text = en Banco Nombre = DireccionTextbos3 text = en Banco Nombre = TelefonoTextbos4 text = en Banco Nombre = NotasCommandButton1 Caption = Anadir Nombre = anadirCommandButton2 Caption = Ver Nombre = VerCommandButton3 Caption = Borrar Nombre = BorrarCommandButton4 Caption = Salir Nombre = SalirComboBox Nombre = ListaTfnosCommonDialog1 Nombre = CommonDialog1

Ingresar al menu de Herramientas y seleccionar Editor de Menus donde aparece el siguiente menú

Para poder realizar alguna operación sobre esta interfece debe pararce en Caption $Fichero, Name: MenuFichero y luego el boton Siguiente, y asi para los siguientes botones

Luego de generar los menú la interface quedara de la siguiente manera:

Page 60: Talleres Visual Basic Basico 2[1]

Option Explicit---------------------------------------------------------------------------Private Sub AyudaAcercaDe_Click() AcercaDe.Show vbModal, Me 'caja de diálogo modalEnd Sub---------------------------------------------------------------------------Private Sub FicheroAbrir_Click() CommonDialog1.Filter = "BD de teléfonos (*.tfn)|*.tfn|" & _ "Todos (*.*)|*.*" ' Filtro por defecto CommonDialog1.FilterIndex = 1 ' Visualizar la caja de diálogo Abrir CommonDialog1.ShowOpen ' CommonDialog1.Filename contiene el camino y ' el nombre del fichero elegido bdTfnos = CommonDialog1.FileName AbrirFicheroEnd Sub---------------------------------------------------------------------------Private Sub AbrirFichero() Dim NumRegsFich As Integer, LongReg As Integer, I As Integer Dim NumFichero As Integer

'Obtener un número libre de fichero NumFichero = FreeFile LongReg = Len(Tfnos(1)) On Error GoTo RutinaErrorAbrir 'Abrir el fichero Open bdTfnos For Random As #NumFichero Len = LongReg NumRegsFich = LOF(NumFichero) \ LongReg 'Leer los registros del fichero For I = 1 To NumRegsFich Get #NumFichero, , Tfnos(I) Next I Close #NumFichero

'Borrar todos los elementos de la lista ListaTfnos.Clear 'Número de elementos de la lista TotalRegs = NumRegsFich

Page 61: Talleres Visual Basic Basico 2[1]

'Añadir los elementos de la matriz a la lista For I = 1 To TotalRegs Form1.ListaTfnos.AddItem Tfnos(I).Nombre Next I 'Visualizar el primer registro Form1.Nombre.Text = Tfnos(1).Nombre Form1.Dirección.Text = Tfnos(1).Dirección Form1.Teléfono.Text = Tfnos(1).Teléfono Form1.Notas.Text = Tfnos(1).NotasSalirAbrir: Exit SubRutinaErrorAbrir: MsgBox "Error: no se puede abrir el fichero", 48, "Tfnos" Close Resume SalirAbrirEnd Sub---------------------------------------------------------------------------Private Sub FicheroGuardar_Click() CommonDialog1.Filter = "BD de teléfonos (*.tfn)|*.tfn|" & _ "Todos (*.*)|*.*" ' Filtro por defecto CommonDialog1.FilterIndex = 1 ' Visualizar la caja de diálogo Guardar como CommonDialog1.ShowSave ' CommonDialog1.Filename contiene el camino y ' el nombre del fichero elegido bdTfnos = CommonDialog1.FileName GuardarFicheroEnd Sub---------------------------------------------------------------------------Private Sub GuardarFichero() Dim I As Integer, Cadena As String Dim NumFichero As Integer ' Obtener un número libre de fichero NumFichero = FreeFile On Error GoTo RutinaErrorGuardar ' Escribir en el fichero Open bdTfnos For Random As #NumFichero Len = Len(Tfnos(1)) If (LOF(NumFichero) <> 0) Then Cadena = "El fichero ya existe" & vbCrLf Cadena = Cadena + "¿desea sobreescribirlo?" If MsgBox(Cadena, 36, "Tfnos") = vbYes Then Close #NumFichero Kill bdTfnos Open bdTfnos For Random As #NumFichero Len = Len(Tfnos(1)) Else Close #NumFichero Exit Sub End If End If ' Escribir los registros de la matriz en el fichero For I = 1 To TotalRegs Put #NumFichero, , Tfnos(I) Next I Close #NumFichero

Page 62: Talleres Visual Basic Basico 2[1]

Form1.Nombre.SetFocusSalirGuardar: Exit SubRutinaErrorGuardar: MsgBox "Error al abrir el fichero", 48, "Tfnos" Resume SalirGuardarEnd Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub Label4_Click()End Sub---------------------------------------------------------------------------Private Sub ListaTfnos_KeyPress(KeyAscii As Integer) Dim I As Integer For I = 0 To TotalRegs - 1 If Left(ListaTfnos.List(I), 1) = Str(KeyAscii) Then ListaTfnos.ListIndex = I Exit For End If Next IEnd Sub---------------------------------------------------------------------------Private Sub menúAyuda_Click()End Sub---------------------------------------------------------------------------Private Sub menúFichero_Click()End Sub---------------------------------------------------------------------------Private Sub Nombre_GotFocus() ' Seleccionar el texto de la caja Nombre.SelStart = 0 Nombre.SelLength = Len(Nombre.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Dirección_GotFocus() ' Seleccionar el texto de la caja Dirección.SelStart = 0 Dirección.SelLength = Len(Dirección.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub

Page 63: Talleres Visual Basic Basico 2[1]

---------------------------------------------------------------------------Private Sub Separador_Click()End Sub---------------------------------------------------------------------------Private Sub Teléfono_GotFocus() ' Seleccionar el texto de la caja Teléfono.SelStart = 0 Teléfono.SelLength = Len(Teléfono.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Notas_GotFocus() ' Seleccionar el texto de la caja Notas.SelStart = 0 Notas.SelLength = Len(Notas.Text) 'Habilitar/inhabilitar controles Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Añadir_Click() If Nombre.Text = "" Or Dirección.Text = "" Or Teléfono.Text = "" Then MsgBox "Complete los campos Dirección, Nombre y Teléfono" Exit Sub End If TotalRegs = TotalRegs + 1 Tfnos(TotalRegs).Nombre = Nombre.Text Tfnos(TotalRegs).Dirección = Dirección.Text Tfnos(TotalRegs).Teléfono = Teléfono.Text Tfnos(TotalRegs).Notas = Notas.Text 'Añadir el Nombre a la lista "ListaTfnos" ListaTfnos.AddItem Nombre.TextEnd Sub---------------------------------------------------------------------------Private Sub Ver_Click() Call VisualizarRegistroEnd Sub---------------------------------------------------------------------------Private Sub ListaTfnos_DblClick() Call VisualizarRegistroEnd Sub---------------------------------------------------------------------------Private Sub Borrar_Click() Dim I As Integer, R As Integer 'Borrar el registro R de la matriz 'Comienza la búsqueda For I = 1 To TotalRegs If (RTrim(Tfnos(I).Nombre) = _ RTrim(ListaTfnos.Text)) Then Exit For End If

Page 64: Talleres Visual Basic Basico 2[1]

Next I If I > TotalRegs Then Exit Sub 'no encontrado 'R = I es el registro a borrar. Se borra, retrocediendo una 'posición todos los registros que estén a continuación del 'registro R que queremos borrar For R = I To TotalRegs - 1 Tfnos(R) = Tfnos(R + 1) Next R 'Borrar los datos del último registro Tfnos(TotalRegs).Nombre = "" Tfnos(TotalRegs).Dirección = "" Tfnos(TotalRegs).Teléfono = "" Tfnos(TotalRegs).Notas = "" 'Actualizar el contador de registros TotalRegs = TotalRegs - 1 'Borrar el nombre que seleccionamos en la lista "ListaTfnos" 'Posición que ocupa el nombre en la lista R = ListaTfnos.ListIndex 'Borrar el nombre ListaTfnos.RemoveItem REnd Sub---------------------------------------------------------------------------Private Sub ListaTfnos_GotFocus() Ver.Enabled = True Borrar.Enabled = True Añadir.Enabled = FalseEnd Sub---------------------------------------------------------------------------Private Sub Form_Load() Ver.Enabled = False Borrar.Enabled = False Añadir.Enabled = TrueEnd Sub---------------------------------------------------------------------------Private Sub Salir_Click() Unload Form1 EndEnd Sub

Ojr esto va en el modulo

Option Explicit

Type Registro Nombre As String * 30 Dirección As String * 30 Teléfono As String * 12 Notas As String * 240End TypePublic Tfnos(1 To 99) As RegistroPublic TotalRegs As IntegerPublic bdTfnos As String

Public Sub VisualizarRegistro() Dim I As Integer, Encontrado As Boolean

Page 65: Talleres Visual Basic Basico 2[1]

Encontrado = False 'elemento no encontrado For I = 1 To TotalRegs If (RTrim(Tfnos(I).Nombre) = _ RTrim(Form1.ListaTfnos.Text)) Then Encontrado = True 'elemento encontrado Exit For End If Next I If (Encontrado) Then Form1.Nombre.Text = RTrim(Tfnos(I).Nombre) Form1.Dirección.Text = RTrim(Tfnos(I).Dirección) Form1.Teléfono.Text = RTrim(Tfnos(I).Teléfono) Form1.Notas.Text = RTrim(Tfnos(I).Notas) Else MsgBox "El nombre especificado no se encuentra", 48, "Tfnos" End IfEnd Sub

Page 66: Talleres Visual Basic Basico 2[1]

34. Veinticuatroavo Ejercicio

Crear las bases de DatosComplementosAdministracion Visual de datosArchivoNuevoMocrosoftMocrosoft AccessMdb Version 7.0

File Name : Tfnos y luego Save

Hacer clck derecho PropietesSeleccionar Nueva Tabla

Page 67: Talleres Visual Basic Basico 2[1]

Nombre de la tabla TfnosBoton Agregar Campo Digitamos en Name NombreBoton Agregar Campo Digitamos en Name DireccionBoton Agregar Campo Digitamos en Name TelefonoBoton Agregar Campo Digitamos en Name NotasBoton CerrarBoton Generar Tabla

Hacer clck derecho TfnosSeleccionar Abrir

Page 68: Talleres Visual Basic Basico 2[1]

Si seleccionamos el boton Agregar vamos a ingresar un nuevo registroSi seleccionamos el boton Modificar vamos a modificar un registroSi seleccionamos el boton Eliminar vamos a eliminar un registroSi seleccionamos el boton Cerrar vamos a cerrar la tablaSi seleccionamos el boton Ordenar vamos a Ordenart los registros por un campoSi seleccionamos el boton filtrar vamos a filtrar la tabla por un campoSi seleccionamos el boton Mover vamos a mover un campoSi seleccionamos el boton Buscar vamos a buscar un campo

Para este ejercicio debes de ingresar por lo menos unos 10 registros que luego veremos en la siguiente interface que sigue a continuacion.

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Telefonos Autoredraw = TrueData 1 DataBasename = Tfnos Recordsource = TfnosLabel1 Caption = NombreLabel2 Caption = DireccionLabel3 Caption = TelefonoLabel4 Caption = NotasTextbos1 text = en Banco DatoSource = Data1 Datafield = NombreTextbos2 text = en Banco DatoSource = Data1 Datafield = DireccionTextbos3 text = en Banco DatoSource = Data1 Datafield = TelefonoTextbos4 text = en Banco DatoSource = Data1 Datafield = NotasCommandButton1 Caption = Nuevo Nombre = NuevoCommandButton2 Caption = Editar Nombre = EditarCommandButton3 Caption = Grabar Nombre = GrabarCommandButton4 Caption = Borrar Nombre = BorrarCommandButton4 Caption = Cancelar Nombre = CancelarCommandButton4 Caption = Refrescar Nombre = RefrescarCommandButton4 Caption = Buscar Nombre = BuscarCommandButton4 Caption = Inicio Nombre = InicioCommandButton4 Caption = Anterior Nombre = AnteriorCommandButton4 Caption = Siguiente Nombre = SiguienteCommandButton4 Caption = Final Nombre = Final

Option Explicit

Page 69: Talleres Visual Basic Basico 2[1]

---------------------------------------------------------------------------Private Sub InhabilitarBotones() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is CommandButton Then Controls(n).Enabled = False End If Next nEnd Sub---------------------------------------------------------------------------Private Sub HabilitarBotones() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is CommandButton Then Controls(n).Enabled = True End If Next nEnd Sub---------------------------------------------------------------------------Private Sub InhabilitarCajas() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is TextBox Then Controls(n).Enabled = False End If Next nEnd Sub---------------------------------------------------------------------------Private Sub HabilitarCajas() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is TextBox Then Controls(n).Enabled = True End If Next nEnd Sub---------------------------------------------------------------------------Private Sub Form_Load() Grabar.Enabled = False InhabilitarCajas ChDir App.PathEnd Sub---------------------------------------------------------------------------Private Sub Inicio_Click() Data1.Recordset.MoveFirstEnd Sub---------------------------------------------------------------------------Private Sub Anterior_Click() Data1.Recordset.MovePrevious If Data1.Recordset.BOF Then Data1.Recordset.MoveFirst End IfEnd Sub---------------------------------------------------------------------------Private Sub Label1_Click()

Page 70: Talleres Visual Basic Basico 2[1]

End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub Label4_Click()End Sub---------------------------------------------------------------------------Private Sub Siguiente_Click() Data1.Recordset.MoveNext If Data1.Recordset.EOF Then Data1.Recordset.MoveLast End IfEnd Sub---------------------------------------------------------------------------Private Sub Final_Click() Data1.Recordset.MoveLastEnd Sub---------------------------------------------------------------------------Private Sub Nuevo_Click() HabilitarCajas InhabilitarBotones Grabar.Enabled = True Cancelar.Enabled = True Data1.Recordset.AddNew 'añadir un nuevo registro Text1.SetFocus 'poner el cursor en la caja del "Nombre"End Sub---------------------------------------------------------------------------Private Sub Editar_Click() HabilitarCajas InhabilitarBotones Grabar.Enabled = True Cancelar.Enabled = True Data1.Recordset.Edit 'editar el registro actual Text1.SetFocus 'poner el cursor en la caja del "Nombre"End Sub---------------------------------------------------------------------------Private Sub Grabar_Click() Data1.Recordset.Update HabilitarBotones Grabar.Enabled = False InhabilitarCajasEnd Sub---------------------------------------------------------------------------Private Sub Cancelar_Click() Data1.UpdateControls HabilitarBotones Grabar.Enabled = False InhabilitarCajasEnd Sub---------------------------------------------------------------------------Private Sub Borrar_Click()

Page 71: Talleres Visual Basic Basico 2[1]

Dim r As Integer On Error GoTo RutinaDeError r = MsgBox("¿Desea borrar el registro?", vbYesNo, "Atención") If r <> vbYes Then Exit Sub Data1.Recordset.Delete 'borrar el registro actual Data1.Recordset.MoveNext 'situarse en el registro siguiente If Data1.Recordset.EOF Then Data1.Recordset.MoveLast End If Exit SubRutinaDeError: r = MsgBox(Error, vbOKOnly, "Se ha producido un error:") Data1.UpdateControlsEnd Sub---------------------------------------------------------------------------Private Sub Refrescar_Click() Data1.Refresh HabilitarBotones Grabar.Enabled = FalseEnd Sub---------------------------------------------------------------------------Private Sub Buscar_Click() Dim Buscado As String, Criterio As String Buscado = InputBox("¿Qué nombre quieres buscar?") Criterio = "Nombre Like '*" & Buscado & "*'" Data1.Recordset.FindFirst Criterio If Data1.Recordset.NoMatch Then MsgBox ("No encuentro ese nombre") Data1.Recordset.MoveLast End IfEnd Sub---------------------------------------------------------------------------Private Sub Text2_Change()End Sub---------------------------------------------------------------------------Private Sub Text3_Change()End Sub---------------------------------------------------------------------------Private Sub Text4_Change()End Sub

Page 72: Talleres Visual Basic Basico 2[1]

35.TreintaCinciavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option Explicit

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, _ X As Single, Y As Single) Print "Se ha pulsado el "; If Button = 1 Then Print "botón izquierdo" If Button = 2 Then Print "botón derecho" If Button = 4 Then Print "botón central"End Sub---------------------------------------------------------------------------Private Sub Form_MouseMove(Button As Integer, Shift As Integer, _ X As Single, Y As Single) If Button = 0 Then Exit Sub If Button = 1 Or Button = 2 Or Button = 4 Then Print "Se pulsó sólo el botón "; If (Button = 1) Then Print "izdo" If (Button = 2) Then Print "dcho" If (Button = 4) Then Print "medio" Else Print "Se pulsaron los botones " If (Button And 1) Then Print "izdo y ?" If (Button And 2) Then Print "dcho y ?" If (Button And 4) Then Print "medio y ?" If (Button And 3) = 3 Then Print "izdo y dcho" If (Button And 5) = 5 Then Print "izdo y central" If (Button And 6) = 6 Then Print "dcho y central" If (Button And 7) = 7 Then Print "izdo, dcho y central" End IfEnd Sub---------------------------------------------------------------------------Private Sub Form_MouseUp(Button As Integer, Shift As Integer, _ X As Single, Y As Single) Print "Se ha soltado el "; If Button = 1 Then Print "botón izquierdo" If Button = 2 Then Print "botón derecho" If Button = 4 Then Print "botón central"End Sub

Page 73: Talleres Visual Basic Basico 2[1]

36.TreintaSeisavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Sub Form_Load() ChDir App.Path Text1.DragMode = vbAutomatic Text1.DragIcon = LoadPicture("DRAG3PG.ICO")End Sub---------------------------------------------------------------------------Private Sub Form_DragDrop(Source As Control, X As Single, Y As Single) Dim CX As Single, CY As Single CX = Source.Width / 2 CY = Source.Height / 2 Source.Move X - CX, Y - CYEnd Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Picture1_DragOver(Source As Control, X As Single, _ Y As Single, State As Integer) If State = vbEnter Then Label1.Caption = "Entra" ElseIf State = vbLeave Then Source.DragIcon = LoadPicture("DRAG3PG.ICO") Label1.Caption = "Sale" ElseIf State = vbOver Then Source.DragIcon = LoadPicture("DROP1PG.ICO") Label1.Caption = "Encima" End IfEnd Sub---------------------------------------------------------------------------Private Sub Picture1_DragDrop(Source As Control, X As Single, Y As Single) Source.DragIcon = LoadPicture("DRAG3PG.ICO") Text1.Text = "" Label1.Caption = "Documento" & vbCrLf & "en la" & vbCrLf & "papelera"End Sub---------------------------------------------------------------------------Private Sub Text1_Change()End Sub

Page 74: Talleres Visual Basic Basico 2[1]

37.TreintaSieteavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = arrastre manual Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private DespX As Single, DespY As SinglePrivate Sub Form_DragDrop(Source As Control, _ X As Single, Y As Single) 'X, Y son las coordenadas del ratón, referidas a Form Picture1.Move X - DespX, Y - DespYEnd Sub---------------------------------------------------------------------------Private Sub Picture1_MouseDown(Button As Integer, _ Shift As Integer, X As Single, Y As Single) 'X, Y son las coordenadas del ratón, referidas a Picture1 Picture1.Drag vbBeginDrag ' iniciar arrastre DespX = X DespY = YEnd Sub

Page 75: Talleres Visual Basic Basico 2[1]

38.TreintaOchoavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption = Eventos del raton Autoredraw = True

Option Explicit---------------------------------------------------------------------------Private Pintar As Boolean Private Sub Form_Load() DrawWidth = 6 'utiliza una pluma de ancho 6 ForeColor = RGB(0, 0, 255) 'tinta de color azulEnd Sub---------------------------------------------------------------------------Private Sub Form_MouseDown(Button As Integer, Shift As Integer, _ X As Single, Y As Single) Pintar = True 'activa la plumaEnd Sub---------------------------------------------------------------------------Private Sub Form_MouseMove(Button As Integer, Shift As Integer, _ X As Single, Y As Single) If Pintar And (Button = vbLeftButton) Then PSet (X, Y) 'dibuja un punto End IfEnd Sub---------------------------------------------------------------------------Private Sub Form_MouseUp(Button As Integer, Shift As Integer, _ X As Single, Y As Single) Pintar = False 'desactiva la plumaEnd Sub

Page 76: Talleres Visual Basic Basico 2[1]

39.TreintaNueveavo Ejercicio

Herramientas a utilizar en la siguiente interface y sus propiedades:

Form1 Caption =controles AciveX Autoredraw = TrueDBGrid1 Caption = Telefonos Recorsource = Data1Data1 DataBaseName = Tfnos Recorsource = TfnosCommandoBotton1 Caption = Borrar SeleccionCommandoBotton2 Caption = Cerrar

Option Explicit---------------------------------------------------------------------------Private Sub Borrar_Click() Dim mReg On Error GoTo RutinaDeError For Each mReg In DBGrid1.SelBookmarks ' Hacer que el registro actual sea el siguiente de ' los registros seleccionados Data1.Recordset.Bookmark = mReg ' Eliminar el registro actual Data1.Recordset.Delete Next Exit SubRutinaDeError: MsgBox Err.DescriptionEnd Sub---------------------------------------------------------------------------Private Sub Cerrar_Click() EndEnd Sub---------------------------------------------------------------------------Private Sub Data1_Validate(Action As Integer, Save As Integer) Dim BotonesIcono As Integer Dim msg As String BotonesIcono = vbYesNo + vbQuestion ' Si la acción es borrar el registro ... If Action = vbDataActionDelete Then msg = "¿Está usted seguro de que quiere eliminar" & vbCrLf & _ "del listín a " & Data1.Recordset.Fields(0) & "?" If MsgBox(msg, BotonesIcono, "¿Borrar registro?") <> vbYes Then Action = vbDataActionCancel 'cancelar la operación

Page 77: Talleres Visual Basic Basico 2[1]

Exit Sub End If End IfEnd Sub---------------------------------------------------------------------------Private Sub DBGrid1_Click()End Sub---------------------------------------------------------------------------Private Sub Form_Load() ChDir App.PathEnd Sub

Page 78: Talleres Visual Basic Basico 2[1]

40.. Veinticuatroavo Ejercicio

Crear las bases de DatosComplementosAdministracion Visual de datosArchivoNuevoMocrosoftMocrosoft AccessMdb Version 7.0

File Name : Multimedia y luego Guardar

Hacer clck derecho PropietesSeleccionar Nueva Tabla

Page 79: Talleres Visual Basic Basico 2[1]

Nombre de la tabla MultimediaBoton Agregar Campo Digitamos en Name NombreBoton Agregar Campo Digitamos en Name TextoBoton Agregar Campo Digitamos en Name VideoBoton Agregar Campo Digitamos en Name ImagenBoton Agregar Campo Digitamos en Name SonidoBoton CerrarBoton Generar Tabla

Hacer clck derecho MultimediaSeleccionar Abrir

Page 80: Talleres Visual Basic Basico 2[1]

Si seleccionamos el boton Agregar vamos a ingresar un nuevo registroSi seleccionamos el boton Modificar vamos a modificar un registroSi seleccionamos el boton Eliminar vamos a eliminar un registroSi seleccionamos el boton Cerrar vamos a cerrar la tablaSi seleccionamos el boton Ordenar vamos a Ordenart los registros por un campoSi seleccionamos el boton filtrar vamos a filtrar la tabla por un campoSi seleccionamos el boton Mover vamos a mover un campoSi seleccionamos el boton Buscar vamos a buscar un campo

Para este ejercicio debes de ingresar por lo menos unos 10 registros que luego veremos en la siguiente interface que sigue a continuacion.

Herramientas a utilizar en la siguiente interface y sus propiedades:Form1 Caption = Telefonos Autoredraw = TrueData 1 DataBasename = MULTIMEDIA Recordsource = MULTIMEDIALabel1 Caption = NombreLabel2 Caption = TexrtoLabel3 Caption = VideoLabel4 Caption = ImagenLabel5 Caption = SonidoTextbos1 text = en Banco DatoSource = Data1 Datafield = NombreTextbos2 text = en Banco DatoSource = Data1 Datafield = TextoTextbos3 text = en Banco DatoSource = Data1 Datafield = VideoTextbos4 text = en Banco DatoSource = Data1 Datafield = ImagenTextbos5 text = en Banco DatoSource = Data1 Datafield = SonidoCommandButton1 Caption = Nuevo Nombre = NuevoCommandButton2 Caption = Editar Nombre = EditarCommandButton3 Caption = Grabar Nombre = GrabarCommandButton4 Caption = Borrar Nombre = BorrarCommandButton4 Caption = Cancelar Nombre = CancelarCommandButton4 Caption = Refrescar Nombre = RefrescarCommandButton4 Caption = Buscar Nombre = BuscarCommandButton4 Caption = Inicio Nombre = InicioCommandButton4 Caption = Anterior Nombre = AnteriorCommandButton4 Caption = Siguiente Nombre = SiguienteCommandButton4 Caption = Final Nombre = Final

Page 81: Talleres Visual Basic Basico 2[1]

Option Explicit---------------------------------------------------------------------------Private Sub InhabilitarBotones() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is CommandButton Then Controls(n).Enabled = False End If Next nEnd Sub---------------------------------------------------------------------------Private Sub HabilitarBotones() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is CommandButton Then Controls(n).Enabled = True End If Next nEnd Sub---------------------------------------------------------------------------Private Sub InhabilitarCajas() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is TextBox Then Controls(n).Enabled = False End If Next nEnd Sub---------------------------------------------------------------------------Private Sub HabilitarCajas() Dim n As Integer For n = 0 To Controls.Count - 1 If TypeOf Controls(n) Is TextBox Then Controls(n).Enabled = True End If Next nEnd Sub

Page 82: Talleres Visual Basic Basico 2[1]

---------------------------------------------------------------------------Private Sub Form_Load() Grabar.Enabled = False InhabilitarCajas ChDir App.PathEnd Sub---------------------------------------------------------------------------Private Sub Inicio_Click() Data1.Recordset.MoveFirstEnd Sub---------------------------------------------------------------------------Private Sub Anterior_Click() Data1.Recordset.MovePrevious If Data1.Recordset.BOF Then Data1.Recordset.MoveFirst End IfEnd Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()End Sub---------------------------------------------------------------------------Private Sub Label4_Click()End Sub---------------------------------------------------------------------------Private Sub Siguiente_Click() Data1.Recordset.MoveNext If Data1.Recordset.EOF Then Data1.Recordset.MoveLast End IfEnd Sub---------------------------------------------------------------------------Private Sub Final_Click() Data1.Recordset.MoveLastEnd Sub---------------------------------------------------------------------------Private Sub Nuevo_Click() HabilitarCajas InhabilitarBotones Grabar.Enabled = True Cancelar.Enabled = True Data1.Recordset.AddNew 'añadir un nuevo registro Text1.SetFocus 'poner el cursor en la caja del "Nombre"End Sub---------------------------------------------------------------------------Private Sub Editar_Click() HabilitarCajas InhabilitarBotones Grabar.Enabled = True Cancelar.Enabled = True

Page 83: Talleres Visual Basic Basico 2[1]

Data1.Recordset.Edit 'editar el registro actual Text1.SetFocus 'poner el cursor en la caja del "Nombre"End Sub---------------------------------------------------------------------------Private Sub Grabar_Click() Data1.Recordset.Update HabilitarBotones Grabar.Enabled = False InhabilitarCajasEnd Sub---------------------------------------------------------------------------Private Sub Cancelar_Click() Data1.UpdateControls HabilitarBotones Grabar.Enabled = False InhabilitarCajasEnd Sub---------------------------------------------------------------------------Private Sub Borrar_Click() Dim r As Integer On Error GoTo RutinaDeError r = MsgBox("¿Desea borrar el registro?", vbYesNo, "Atención") If r <> vbYes Then Exit Sub Data1.Recordset.Delete 'borrar el registro actual Data1.Recordset.MoveNext 'situarse en el registro siguiente If Data1.Recordset.EOF Then Data1.Recordset.MoveLast End If Exit SubRutinaDeError: r = MsgBox(Error, vbOKOnly, "Se ha producido un error:") Data1.UpdateControlsEnd Sub---------------------------------------------------------------------------Private Sub Refrescar_Click() Data1.Refresh HabilitarBotones Grabar.Enabled = FalseEnd Sub---------------------------------------------------------------------------Private Sub Buscar_Click() Dim Buscado As String, Criterio As String Buscado = InputBox("¿Qué nombre quieres buscar?") Criterio = "Nombre Like '*" & Buscado & "*'" Data1.Recordset.FindFirst Criterio If Data1.Recordset.NoMatch Then MsgBox ("No encuentro ese nombre") Data1.Recordset.MoveLast End IfEnd Sub---------------------------------------------------------------------------Private Sub Text2_Change()End Sub---------------------------------------------------------------------------Private Sub Text3_Change()

Page 84: Talleres Visual Basic Basico 2[1]

End Sub---------------------------------------------------------------------------Private Sub Text4_Change()End Sub

Herramientas a utilizar en la siguiente interface y sus propiedades:Proyecto Agregar Formulario

Seleccionar Abrir

ProyectoCompenentesSeleccionamos Microsoft Internet Controls y Windows Media Player

Form2 Caption = Multimedia2 Autoredraw = TrueData 1 DataBasename = MULTIMEDIA Recordsource = MULTIMEDIALabel1 Caption = NombreLabel2 Caption = TexrtoLabel3 Caption = VideoLabel4 Caption = Imagen

Page 85: Talleres Visual Basic Basico 2[1]

Label5 Caption = SonidoTextbos1 Nombre = Titulo DatoSource = Data1 Datafield = NombreTextbos2 Nombre = Texto DatoSource = Data1 Datafield = TextoTextbos3 Nombre = Video DatoSource = Data1 Datafield = VideoTextbos4 Nombre = Imagen DatoSource = Data1 Datafield = ImagenTextbos5 Nombre = Sonido DatoSource = Data1 Datafield = SonidoWebBrowser1 Nombre = TextosWindowsmediaPlayer Nombre = Videos Personalizar = Rebobinar al terminarImage Nombre= Imágenes Stretch=traeWindowsmediaPlayer Nombre = Sonidos Personalizar = Rebobinar al terminar

Private Sub Form_Load() Textos.Navigate (Texto.Text) Videos.URL = (Video.Text) Fotos.Picture = LoadPicture(Foto.Text) End Sub---------------------------------------------------------------------------Private Sub Videp_Change()End Sub---------------------------------------------------------------------------Private Sub Foto_Change()End Sub---------------------------------------------------------------------------Private Sub Fotos_Click()End Sub---------------------------------------------------------------------------Private Sub Label1_Click()End Sub---------------------------------------------------------------------------Private Sub Label2_Click()End Sub---------------------------------------------------------------------------Private Sub Label3_Click()

Page 86: Talleres Visual Basic Basico 2[1]

End Sub---------------------------------------------------------------------------Private Sub label4_Click()End Sub---------------------------------------------------------------------------Private Sub Label5_Click()End Sub---------------------------------------------------------------------------Private Sub Sonido_Change()End Sub---------------------------------------------------------------------------Private Sub Texto_Change()End Sub---------------------------------------------------------------------------Private Sub Textos_StatusTextChange(ByVal Text As String)End Sub---------------------------------------------------------------------------Private Sub titulo_Change()End Sub---------------------------------------------------------------------------Private Sub Video_Change()End Sub---------------------------------------------------------------------------Private Sub Videos_OpenStateChange(ByVal NewState As Long)End Sub