Está en la página 1de 15

APUNTES DE VBA EXCEL

Trabajando en una hoja activa


Valor por defecto: Value
Range(“b5”).value = 250
Range(b5”) = 250

Trabajando sin hoja active


Application. Workbooks(“libro1”).Worksheets(“hoja2”).
range(“B5”).value = 250

Módulos: Organizadores de procedimientos

Para borrar celdas seleccionadas


Sub borrar()
Range("b5").Select (selecciona celdas que deseas)
Selection.ClearContents (borra todo lo seleccionado)
End Sub

Para borrar celda por celda o celda específica


Range("b5").ClearContents (borra contenido)
Range("b5").Clear (borra todo)
DESTACAR (Colorear la celda)
Sub destacar()
Range("b5").Interior.Color = 255 (255 código para color rojo)
End Sub

Sub destacar()
Range("b5").Interior.Color = vbred (si pones como prefijo /vb/,
puedes poner el nombre del color en inglés.
Range("b5").Interior.Color = RGB(100,100,100) (Color a partir
de la combinación RGB)
End Sub

TIPOS DE DATOS
 Byte valores de 0 a 255
 Integer almacenar números enteros desde -32768 al 32767
 Long Números enteros grandes -2B hasta 2B
 Single Números decimales con parte decimal corta
 Double Números decimales con parte decimal larga
 Decimal Números decimales con parte decimal
extremadamente larga
 Boolean solo toma dos valores: verdadero (true) falso (false)
 Currency tipo moneda
 Object objeto
 String Cadena de caracteres
 Variant dato sin especificar
Dim nombre as string
nombre = “Antony”
Sub tipos_datos()
Dim nombre As String
nombre = "Antony"
Dim edad As Byte
edad = 22
MsgBox "Hola " & nombre & "," & " tienes " & edad & " años"
Declaración de variables
Ejm sin declarar variable
Sub declaración_variables() (NO RECOMENDADO)
minombre = "Antony"
MsgBox minombre
End Sub

Opción para avisar que no has declarado variable, exige declarar


variable
Dim minombre as string VARIABLE
minombre = "Antony"
MsgBox minombre
Para declarar un valor en específico

Const valor = 7
O también se puede declarar
Const valor as integer = 7 CONSTANTE

Ejemplo
Sub salario()
'Yo gano 1000 dólares al mes
Const soles As Double = 3.38
Dim salario As Currency
salario = 1000
salario = salario * soles
MsgBox "Tu salario en nuevos soles es de " & salario
End Sub

CREACIÓN DE MATRICES Sirve para crear valores de igual variable


en una sola declaración
Sub declaración_matrices()
Dim mirango(4) As Integer
mirango(0) = 5
mirango(1) = 7
mirango(2) = 4
mirango(3) = 9
mirango(4) = 12
MsgBox mirango(3)
End Sub

Dim mirango(5) As Integer declaro matriz


Dim micelda As Range declare variable tipo objeto
Dim indice As Integer declare variable tipo entero
Range("d1").Select Seleccionar celda mencionada
Selection.CurrentRegion.Select Celdas adyacentes a la celda
seleccionada
For Each micelda In Selection Por cada celda que hay en la seleción
mirango(indice) = micelda.Value
indice = indice + 1 A la siguiente vuelta del bucle tomará un valor
más (siguiente)
Next micelda
DECLARAR MATRICES DE UNA DIMENSIÓN
Sub introducir_valores()
Dim mirango(5) As Integer
Dim micelda As Range
Dim indice As Integer
Range("d1").Select
Selection.CurrentRegion.Select
For Each micelda In Selection
mirango(indice) = micelda.Value
indice = indice + 1
Next micelda
Dim i As Integer
For i = 0 To 5 Step 1
Debug.Print mirango(i)
Next i
End Sub
VARIABLE OBJETO
Sub variable_objeto()
Dim micelda As Range
Set micelda = Range("b2")
micelda = 100
'Range("b2") = 125
'Range("b2").Font.Bold = True
'Range("b2").Font.Italic = True
End Sub

Sub variable_objeto()
Dim micelda As Range
Set micelda = Range("b2")
'micelda = 100
'micelda.Font.Italic = True
'micelda.Font.Bold = True
'Range("b2") = 125
'Range("b2").Font.Bold = True
'Range("b2").Font.Italic = True
With micelda
.Value = 125
.Font.Bold = True
.Font.Italic = True
End With
End Sub
Sub variable_objeto()
Dim micelda As Range
Set micelda = Range("d3:d7")
micelda.Select
For Each micelda In Selection
MsgBox micelda.Value
Next micelda
End Sub
COLOREAR CON CONDICION

Sub variable_objeto()
Dim micelda As Range
For Each micelda In Selection
If micelda.Value > 300 Then
micelda.Interior.Color = vbRed
End If
Next micelda
End Sub

Dim micelda As Range


Dim z As Boolean
For Each micelda In Selection
If WorksheetFunction.IsText(micelda) Then
z = True
End If
Next micelda
If z = True Then
MsgBox "Hay texto en el rango selecionado." & vbCrLf &
"¿Desea continuar?"
Else
MsgBox "Son solo números"
End If
End Sub

Sub funciones_integradas()
Dim micelda As Range
Dim z As Boolean
Dim valor As Integer
For Each micelda In Selection
If WorksheetFunction.IsText(micelda) Then
z = True
End If
Next micelda
If z = True Then
valor = MsgBox("Hay texto en el rango selecionado." & vbCrLf &
"¿Desea continuar?", vbYesNo)
If valor = vbYes Then
MsgBox WorksheetFunction.Sum(Selection)
Else
MsgBox "No se realizará la suma"
End If
Else
MsgBox WorksheetFunction.Sum(Selection)
End If
End Sub

Sub uso_inputbox()
Dim var1 As Integer
Dim var2 As Integer
var1 = InputBox("Introduce el primer n°") (Lo que el usuario
ponga en el input box)
var2 = InputBox("Introduce el segundo n°")
MsgBox "La suma de los números es " & var1 + var2
End Sub

ESTRUCTURAS DE CONTROL DE FLUJO


 CONDICIONALES
o IF- THEN
o SELECT – CASE

 BUCLE (Para evitar programar de uno a uno)


o DETERMINADOS
 For – next
 For – each - next
o INDETERMINADOS
 Do – loop
 While – wend
 Do – until

Sub control_flujo1()
On Error GoTo etiqueta
Dim edad As Integer
edad = InputBox("Introduce tu edad")
If edad < 18 Then
MsgBox "Eres menor de edad"
End If
If edad >= 18 Then
MsgBox "Eres mayor de edad"
End If
Exit Sub
etiqueta:
MsgBox "No sé qué edad tienes"
End Sub

Sub ventas()
Dim micelda As Range
For Each micelda In Selection
If micelda.Offset(0, 1).Value > 500 And micelda.Offset(0, 1).Value <
1000 Then
micelda.Offset(0, 2).Value = micelda.Value + micelda.Offset(0.1) *
0.02
ElseIf micelda.Offset(0, 1).Value >= 1000 And micelda.Offset(0,
1).Value <= 2000 Then
micelda.Offset(0, 2).Value = micelda.Value + micelda.Offset(0.1) *
0.04
Else
micelda.Offset(0, 2).Value = micelda.Value + micelda.Offset(0.1) *
0.07
End If
Next micelda
End Sub

Sub ventas()

Dim micelda As Range

For Each micelda In Selection

Select Case micelda.Offset(0, 1)


Case 500 To 1000
micelda.Offset(0, 2).Value = micelda.Value + micelda.Offset(0,
1).Value * 0.02
Case 1001 To 2000
micelda.Offset(0, 2).Value = micelda.Value + micelda.Offset(0,
1).Value * 0.04
Case Else
micelda.Offset(0, 2).Value = micelda.Value + micelda.Offset(0,
1).Value * 0.07
End Select
Next micelda

End Sub

EJERCICIO GUARDADO EN CARPETA EXCEL VBA

También podría gustarte