You are on page 1of 19

EJEMPLO1

MARCA EL RANGO DE A1 A A29


Sub EJEMPLO1()
Range("A1:A29").Select
End Sub

EJEMPLO2
COLOCA 1 EN LA CEL DA A1 Y LUEGO SE UBICA EN LA CELDA A2
Sub MACRO1()
Range("A1").Select
ActiveCell.FormulaR1C1 = "1"
Range("A2").Select
End Sub

EJEMPLO3
COLOCA 1 EN LA CELDA ACTIVA Y LUEGO SE UBICA EN A2
Sub MACRO2()
ActiveCell.FormulaR1C1 = "1"
Range("A2").Select
End Sub

EJEMPLO4
PONE UN COMENTARIO EN LA CELDA CORRESPONDIENTE
Sub EJEMPLO3A()
Range("C8").Select
ActiveCell.FormulaR1C1 = "MICROSOFT WORD"

Range("C9").Select
ActiveCell.FormulaR1C1 = "WINDOWS"
Range("C10").Select
ActiveCell.FormulaR1C1 = "MICROSOFT EXCEL"
Range("C11").Select
ActiveCell.FormulaR1C1 = "POWER POINT"
Range("C12").Select
ActiveCell.FormulaR1C1 = "ACCESS"
Range("C13").Select
ActiveCell.FormulaR1C1 = "VISUAL BASIC"
Range("C14").Select
End Sub

EJEMPLO5
PONE LOS COMENTARIOS EN LAS FILAS CORRESPONDIENTES

Sub EJEMPLO3C()
ActiveCell.Offset(0, 0) = "MICROSOFT WORD"
ActiveCell.Offset(1, 0) = "WINDOWS"
ActiveCell.Offset(2, 0) = "MICROSOFT EXCEL"
ActiveCell.Offset(3, 0) = "POWER POINT"
ActiveCell.Offset(4, 0) = "ACCESS"
ActiveCell.Offset(5, 0) = "VISUAL BASIC"
End Sub

EJEMPLO6
PONE LOS COMENTARIOS EN LAS COLUMNAS CORRESPONDIENTES
Sub EJEMPLO3B()
ActiveCell.Offset(0, 0) = "MICROSOFT WORD"
ActiveCell.Offset(0, 1) = "WINDOWS"
ActiveCell.Offset(0, 2) = "MICROSOFT EXCEL"
ActiveCell.Offset(0, 3) = "POWER POINT"
ActiveCell.Offset(0, 4) = "ACCESS"
ActiveCell.Offset(0, 5) = "VISUAL BASIC"
End Sub
EJEMPLO07
ESTE PROGRAMA, EN PRIMER LUGAR, PREGUNTAR LA EDAD Y GUARDAR LA
INFORMACIN EN LA VARIABLE AOS.
LUEGO, CON IF, COMPARAR LA EDAD Y SI ES SUPERIOR A 18 DEBE IR A LA
LNEA MAYOR, EN ESTE CASO, EMITIR EL MENSAJE: ERES MENOR DE EDAD,
NO PUEDES USAR ESTE PROGRAMA Y LO CERRAR.
SI ES MAYOR DE EDAD, PEDIR INGRESAR EL NMERO DE DNI Y SIMPLEMENTE
VERIFICAR QUE SEA MAYOR A 999999, EN TAL CASO, IR A LA LNEA DE
INGRESO Y SE LE DAR UNA CLAVE. DE SER MENOR, SALDR EL MENSAJE:
ERES MENOR, NO PUEDES USAR ESTE PROGRAMA Y LO CERRAR.

Sub MACRO_IF()
AOS = InputBox("CUNTOS AOS TIENES")
If AOS >= 18 Then GoTo MAYOR
MsgBox ("ERES MENOR NO PUEDES USAR ESTE PROGRAMA")
Exit Sub
MAYOR:
MsgBox ("ERES MAYOR DE EDAD")
DNI = InputBox("CUAL ES EL NMERO DE DNI_")

If DNI > 999999 Then GoTo INGRESO


MsgBox ("ERES MENOR NO PUEDES USAR ESTE PROGRAMA")
Exit Sub
INGRESO:
MsgBox ("TU CLAVE DE INGRESO ES XX23")
End Sub
EJEMPLO08
CREAR UNA MACRO QUE PREGUNTE LA EDAD Y DE ACUERDO A LA RESPUESTA
ESCRIBA:
ERES MASTER, SI LA EDAD ES IGUAL O SUPERIOR A 40
ERES ADULTO, SI LA EDAD ES IGUAL O SUPERIOR A 18 E INFERIOR A 40
ERES ADOLECENTE, SI LA EDAD ES IGUAL O SUPERIOR A 12 E INFERIOR A 18
ERES NIO, SI LA EDAD ES IGUAL O SUPERIOR A 6 E INFERIOR A 12 Y
ERES BEBE, SI LA EDAD ES IGUAL O INFERIOR A 6 AOS.

Sub MACROIF2()
AOS = InputBox("CUNTOS AOS TIENES")
If AOS >= 40 Then MsgBox ("ERES MSTER")
If AOS < 40 And AOS >= 18 Then MsgBox ("ERES ADULTO")
If AOS >= 12 And AOS < 18 Then MsgBox ("ERES ADOLECENTE")
If AOS < 12 And AOS > 6 Then MsgBox ("ERES NIO")
If AOS <= 6 Then MsgBox ("ERES BEBE")
Exit Sub
End Sub

CREAR FORMULARIOS CON VB

Crearemos un formulario para luego programarlos por medio de un cuadro de


controles de acuerdo con los requerimientos del ejercicio que deseemos
realizar.
Ingresaremos al editor de VB
. ALT + F11
. Ingresamos al Cdigo de la ficha Programador
Para crear un formulario ingresaremos
. Al men VER y elegiremos Explorador de Proyectos
. Al men VER y elegiremos Ventana Propiedades
Ahora ingresamos al men insertar y elegimos la opcin UserForm
El editor de del VB est listo para trabajar.
INGRESAR ETIQUETAS
Seleccionamos el cono
del cuadro de herramientas y en el formulario
pulsamos sobre un punto y , sin soltar, arrastramos hasta tener el tamao
necesario. Para escribir damos un clic. En este caso digitaremos LONGITUD DE
LA VIGA.
INGRESAR UN CUADRO TEXTO
Ahora seleccionaremos el cono
del cuadro de herramientas y en el
formulario pulsamos sobre un punto y, sin soltar, arrastramos hasta tener el
tamao necesario.
De la misma forma ingresamos las etiquetas y cuadros de texto siguientes:

Las etiquetas son textos que van sobre el formulario, pero no tienen
vinculacin directa con variables ni funciones.
Los cuadros de texto si estn relacionados y cada uno de ellos tiene el nombre
de una variable que por defecto es textobox1. Conforme creamos un cuadro
de texto la numeracin de la variable cambia textobox2, textobox3,
textobox4 y textobox5.
VINCULAR EL CONTENIDO DE LOS CUADROS DE TEXTO TEXTBOX
Vincularemos los cuadros de texto de la siguiente manera:
Textbox1

A la celda B5

Textbox2

A la celda C5

Textbox3

A la celda D5

Textbox4

A la celda G5

Textbox5

A la celda G7

Textbox1 a la celda B5
Nos ubicamos en el cuadro de texto 1 y le damos doble clic

El programa nos enva a la opcin Ver Cdigo, donde ya se encuentra creado el


programa para el cuadro de texto y agregamos el cdigo:
Range("B5").Select
ActiveCell.FormulaR1C1 = TextBox1
Para que al final quede:
Private Sub TextBox1_Change()
Range("B5").Select
ActiveCell.FormulaR1C1 = TextBox1
End Sub
Hacemos lo mismo con el resto de cuadros texto y al final agregamos un botn
que borre los valores que le llamaremos
doble clic en l y agregamos el cdigo:
TextBox1 = Empty
TextBox2 = Empty
TextBox3 = Empty
TextBox4 = Empty

, hacemos

TextBox5 = Empty
Al final el cdigo de la Macro realizada en VB es el siguiente:
Private Sub TextBox1_Change()
Range("B5").Select
ActiveCell.FormulaR1C1 = TextBox1
End Sub
Private Sub TextBox2_Change()
Range("C5").Select
ActiveCell.FormulaR1C1 = TextBox2
End Sub
Private Sub TextBox3_Change()
Range("D5").Select
ActiveCell.FormulaR1C1 = TextBox3
TextBox4 = 1.4 * Val(TextBox2) + 1.7 * Val(TextBox3)
End Sub
Private Sub TextBox4_Change()
Range("G5").Select
ActiveCell.FormulaR1C1 = TextBox4
TextBox5 = Val(TextBox4) * Val(TextBox1) * Val(TextBox1) / 12
End Sub
Private Sub TextBox5_Change()
Range("G7").Select
ActiveCell.FormulaR1C1 = TextBox5
End Sub
Private Sub CommandButton1_Click()
TextBox1 = Empty

TextBox2 = Empty
TextBox3 = Empty
TextBox4 = Empty
TextBox5 = Empty
End Sub

CDIGO NUMRICO DEL CASO ANTERIOR:

Dim v1 As Double, v2 As Double, v3 As Double, v4 As Double, v5 As Double


Private Sub TextBox1_Change()
If IsNumeric(TextBox1.Text) Then
Range("B5").Select
ActiveCell.FormulaR1C1 = TextBox1
If Len(TextBox1.Text) > 0 Then
v1 = CDbl(TextBox1)
End If
End If
End Sub
Private Sub TextBox2_Change()
Range("C5").Select
ActiveCell.FormulaR1C1 = TextBox2
If Len(TextBox2.Text) > 0 Then
v2 = CDbl(TextBox2)
End If

End Sub
Private Sub TextBox3_Change()
Range("D5").Select
ActiveCell.FormulaR1C1 = TextBox3
If Len(TextBox3.Text) > 0 Then
v3 = CDbl(TextBox3)
End If

v4 = 1.4 * v2 + 1.7 * v3
TextBox4 = Format(v4, "##.00")
End Sub
Private Sub TextBox4_Change()
Range("G5").Select
ActiveCell.FormulaR1C1 = v4
v5 = v4 * v1 ^ 2 / 12
TextBox5 = v5
End Sub
Private Sub TextBox5_Change()
Range("G7").Select
ActiveCell.FormulaR1C1 = v5
End Sub
Private Sub CommandButton1_Click()
TextBox1 = Empty
TextBox2 = Empty
TextBox3 = Empty
TextBox4 = Empty
TextBox5 = Empty
End Sub

CREAR LA MACRO PARA ENTRADA DESDE EXCEL


Para ingresar directamente desde MS Excel, necesitamos crear una macro
adicional.

El formulario UserForm1 se encuentra en la carpeta Formulario. La macro que


queremos debe estar dentro de un modulo y se encontrar en al carpeta
modulo.
Para crear esta macro debemos ingresar al menu Insertar y seleccionar la
opcin Mdulo.
En ella escribimos el nombre de la macro VIGA y los commandos Load y
Show.

Con Load UserForm1 se lee el formulario 1 y con UserForm1.Show se


muestra el formulario.

CREAR FUNCIONES CON VB


Para crear una function damos los siguientes pasos:
-

Ingresamos al editor de VB
Insertamos un mdulo
En el escribimos:
Function NOMBRE(X)

En forma automtica aparecer el cierre de la funcin


Function NOMBRE(X)
End function

Ahora ingresamos el contenido para que la funcin NOMBRE compare el


contenido de la celda X y escriba HOLA X COMENXAMOS A TRABAJAR.
Function nombre(x)
nombre = "HOLA " & x & " COMENZAMOS A TRABAJAR! "
End Function

Para usar la funcin:


-

Regresamos a MS Excel , men ARCHIVO, opcin CERRAR y VOLVER A


MS EXCEL
Nos ubicamos en la celda C4 y al solo ingresar las primeras letras de la
funcin, sta aparecer en el listado de funciones.

Seleccionamos la funcin y activamos la celda C2.

Al dar clic a ENTER, la funcin ejecutar sus instrucciones y escribir su


contenido

El siguiente caso se trata de calcular el peso por toneladas de una viga y su


mximo momento negativo, podemos hacer esto usando frmulas, lo hemos
resuelto creando una macro y ahora lo resolveremos creando dos funciones.

SOLUCIN
Ingresamos al editor de VB y en l creamos la funcin WU y momentomax.
Crear la funcin WU
Function WU(X,Y)
WU=1.4*X+1.7*Y
End Function
Observemos que estamos utilizando dos variables (x,y), es decir, para realizar
la funcin seleccionaremos dos celdas por separado.
Crear funcin momentomax
Function momentomax(X,Y,Z)
momentomax=(1.4*X+1.7*Y)*Z*Z/12
End Function
Ahora hemos utilizado dos variables

Ejecutamos las funciones:


-

Regresamos a MS Excel , men ARCHIVO, opcin CERRAR y VOLVER A


MS EXCEL
Nos ubicamos en la celda C7, digitamos la funcin y seleccionamos las
celdas D5 y E5 =WU(D5,E5); al presionar ENTER en forma automtica
aparecer el resultado.
Nos ubicamos en la celda C9, digitamos la funcin y seleccionamos las
celdas D5, E5 y C5 =momentomax(D5,E5,C5)

LLENAR UNA TABLA DE DATOS

MODIFICAMOS EL CDIGO GRABADO DE TAL MANERA QUE QUEDE:


Sub Macro6()
'
' Macro6 Macro
'
' Acceso directo: Ctrl+Mays+D
'
Do
Range("A1").Select
Selection.End(xlDown).Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = InputBox("INGRESE CDIGO...")
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = InputBox("INGRESE NOMBRE...")

ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = InputBox("INGRESE NOTA 1...")
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = InputBox("INGRESE NOTA 2...")
ActiveCell.Offset(-1, 1).Range("A1").Select
Selection.AutoFill Destination:=ActiveCell.Range("A1:A2"), Type:= _
xlFillDefault
ActiveCell.Range("A1:A2").Select
ActiveCell.Offset(2, -4).Range("A1").Select
Loop Until (MsgBox("DESEA CONTINUAR: ", vbYesNo) = vbNo)
End Sub

You might also like