Está en la página 1de 47

¿Qué es una macro?

La definición más común de una macro


es que se trata de un pequeño programa
que sirve para automatizar tareas
repetitivas. Normalmente se guarda en
el mismo libro Excel en cual se va a
ejecutar, pero se puede guardar en otros
libros Exel, tanto como en libros Add-in.

Cuando ese programa crezca, podrá empezar a llamarse programa. Pero si hablamos de
un programita que sirve para ejecutar sencillas, repetitivas tareas, debemos llamarlo
macro.

El nombre macro vendrá de ‘macro-instrucciones’ que así se llamaban antes. Supongo


que se referirían a ‘instrucciones que iban más allá de los menús’.

¿Para qué sirven las macros?

Para cualquier trabajo realizado en Excel, prácticamente. Puedes automatizar procesos,


importaciones de Access, dar un formato predefinido (por ti) a las celdas seleccionadas,
atajo para mandar el último Pivot de Excel a Outlook…

Cómo grabar una macro Excel VBA


Para aprender a programar VBA de Excel la mejor manera de empezar es
probablemente la grabación de macros en Excel. Es fácil grabar tus propias macros. Y
con un ligero retoque, salen todavía mejor.

Preparar la grabación

Entra Herramientas – Macro – Grabar nueva macro.

1
Pon un nombre descriptivo, por ejemplo
Nombre de la macro DosDecimales. Si quieres espacio entre palabras,
pon Dos_Decimales.
Si quieres que la macro se active desde el teclado,
pon la combinación, por ejemplo CTRL + L.
Método abreviado (atajo)
Presionando MAYUSCULA te darán todavía más
combinaciones.
O se guarda en Este Libro, o en Libro de Macros
Personales. Si eliges Libro de Macros Personales,
Guardar macro en
la macro va a estar disponible desde cualquier
libro de Excel.
Si quieres puedes poner un texto explicativo el
Descripción
cual se incluirá en el código de la macro.

Presiona OK. Ahora la macro grabará todo lo que pase a tu libro de Excel. Si
seleccionas celda H1, esa misma acción se grabará. Después, al ejecutar la macro, esa
celda se seleccionará (¡sorpresa…!). Entonces, mientras grabas, selecciona celda H1,
cambia el formato a Número – 2 decimales. Paramos la grabación.

Editar la macro grabada

Entra el VBA editor (Herramientas- Macro – Visual Basic Editor).

Entra Módulos – Módulo 1. A la derecha se ve lo que VBA te ha grabado. El código


hace que Excel selecione celda H1, y que luego aplique un formato de número de dos
decimales. Es decir, la macro solo actuará sobre la celda H1.

Al cambiar el código un poco podremos hacer que VBA cambie el formato a cualquier
celda que tengas seleccionada. Limpia el código para que quede el siguiente marcado.

Selection.NumberFormat = "0.00"

Ejecutar la macro

Ahora, vuelve a la hoja, y prueba tú nueva macro. Selecciona un rango de celdas, aplica
el atajo (CTRL+L). También puedes ejecutar la macro desde Herramientas – Macro –
Macros.

2
Macros personales en Excel
¿Qué son las macros personales?

Son macros accesibles desde cualquier libro


Excel, y estas macros se guardan en un libro
especial llamado Personal.xls (Libro de Macros
Personales).

Al abrir Excel, este libro se cargará,


ocultamente. De este modo, las macros que
grabes allí siempre estarán accesibles. Esto es
una solución eficaz para tus propios atajos, cómo por ejemplo Separador de miles, Pegar
valor etc.

Sobre el libro Personal.xls

Es un libro Excel normal y corriente, pero con unas determinadas características:

• Tiene el nombre de Personal.xls


• Contiene código VBA para tus macros, funciones etc.
• Se carga automáticamente al iniciar Excel
• Tiene el atributo Hidden (escondido) activado (Ventana – Mostrar)
• Se guarda en uno de estos dos sitios (normalmente) :
c:Program FilesMicrosoft OfficeOfficeInicioXL (XLStart)
c:Documents and Settings -user name-Application DataMicrosoftExcelInicioXL

¿Cómo se crea el libro Personal.xls?

Hay dos maneras de crear este libro.

1. Por tu cuenta

Crea un libro nuevo. Guárdalo en la carpeta InicioXL indicado arriba. Vuelve a Excel
para luego ocultar este libro (Ventana – Ocultar). Luego, para colocar macros dentro de
tu nuevo libro, puedes introducirlas manualmente (a través del editor VBA) o
simplemente grabar una macro nueva y guardarla dentro del Libro de Macros
personales..

2. Dejar que Excel te ayude

Al grabar una macro debes indicar donde guardarla. Al elegir el Libro de macros
personales, Excel creará el libro Personal.xls en la carpeta InicioXL.

3
Alternativas a macros personales

En vez de colocar tus macros en el Libro de Macros Personales, podrías crear un Add-in
(Complemento). Este es un libro [.xla] que se carga cada vez que abres Excel (igual que
el Libro de Macros Personales), que no está ocultado pero tampoco visible.

Ejemplos de macros Excel VBA


Ponemos a tu disposición una lista de
ejemplos de macros personales de
Excel que pueden ser útiles en tu
trabajo diario. Recordamos que las
macros Excel VBA ofrecen infinidad
de posibilidades – trata de encontrar las
tareas repetitivas y de ahí crear las
macros.

Unos ejemplos de aplicaciones de macros Excel VBA: Cambiar propiedades de las


hojas Excel, suprimir filas, aplicar los formatos más comunes… En poco tiempo tendrás
unas macros imprescindibles, y ya no podrás trabajar en Excel sin ellas.

Grabar y programar macros de Excel es una estupenda (posiblemente la mejor) manera


de empezar a aprender Visual Basic para Excel (VBA).

Alineación izquierda/derecha
Sub Ajustar_izq_der()
If Selection.HorizontalAlignment = xlRight Then
Selection.HorizontalAlignment = xlLeft
Else
Selection.HorizontalAlignment = xlRight
End If
End Sub

Convertir pesetas a euro


Sub Convertir()
Set Area = Selection
For Each Cell In Area
z = Round(Cell / 166.386, 2)
Cell.Value = z
Cell.NumberFormat = "#,##0.00"
Next Cell
End Sub

Pegar formato
Sub PegarFormato()
Selection.PasteSpecial Paste:=xlFormats
Application.CutCopyMode = False
End Sub

4
Pegar valor
Sub PegarValor()
Selection.PasteSpecial Paste:=xlValues
Application.CutCopyMode = False
End Sub

Dos decimales
Sub DosDec()
Dim Area As Range
Set Area = Selection
For Each Cell In Area
z = Round(Cell, 2)
Cell.Value = z
Cell.NumberFormat = "#,##0.00"
Next Cell
End Sub

Separador de miles
Sub SeparadorMil()
Dim Area As Range
Set Area = Selection
If Area.NumberFormat = "#,##0" Then
Area.NumberFormat = "#,##0.00"
Else
Selection.NumberFormat = "#,##0"
End If
End Sub

Suprimir filas vacías


Sub SuprimirFilasVacias()
LastRow = ActiveSheet.UsedRange.Row - 1 + _
ActiveSheet.UsedRange.Rows.Count
For r = LastRow To 1 Step -1
If Application.CountA(Rows(r)) = 0 Then
Rows(r).Delete
End If
Next r
End Sub

Autofilter
Sub FilterExcel()
Selection.AutoFilter
End Sub

Grids (Líneas de división)


Sub Grids()
If ActiveWindow.DisplayGridlines = True Then
ActiveWindow.DisplayGridlines = False
Else
ActiveWindow.DisplayGridlines = True
End If
End Sub

5
Cambiar A1 a RC (columnas tiene números en vez de letras)
Sub Rc()
If Application.ReferenceStyle = xlR1C1 Then
Application.ReferenceStyle = xlA1
Else
Application.ReferenceStyle = xlR1C1
End If
End Sub

Modificar paleta de colores


Sub ModificarPaleta()
ActiveWindow.Zoom = 75
ActiveWorkbook.Colors(44) = RGB(236, 235, 194)
ActiveWorkbook.Colors(40) = RGB(234, 234, 234)
ActiveWorkbook.Colors(44) = RGB(236, 235, 194)
End Sub

Mostrar todas las hojas


Sub MostrarHojas()
Set wsHoja = Worksheets
For Each wsHoja In ActiveWorkbook.Worksheets
If wsHoja.Visible = False Then
wsHoja.Visible = True
End If
Next wsHoja
End Sub

Introducción a VBA de Excel


VBA (Visual Basic for Applications) es un lenguaje de macros utilizado para programar
pequeñas aplicaciones dentro de un documento Excel, permitiendo la ampliación de la
funcionalidad del mismo.

¡Aprende a programar macros Excel!

VBA es una modalidad adaptada del conocido lenguaje de programación Visual Basic,
incluida en la mayoría de las aplicaciones MS Office como Excel, Word y Access. Una
diferencia entre VBA y Visual Basic es que el programa VBA no se puede separar del
documento Excel, sino queda totalmente integrado dentro del libro de trabajo.

Esta introducción a Excel VBA te enseñará como empezar a desarrollar tus propias
macros Excel. VBA Excel y sus macros constituyen una ayuda potente para particulares
y pequeñas y medianas empresas.

Excel, y sobre todo la aplicación de macros VBA, mejora prácticamente cualquier


proceso de trabajo, desde sencillos cálculos sobre la economía familiar hasta complejos
modelos empresariales de Excel para crear informes, presupuestos y demás documentos
financieros.

6
¿Todo el mundo puede aprender a programar macros?

Si, sin duda. Mucha gente empieza por la grabación de macros, es decir grabar una
secuencia de comandos, para luego reutilizarla. Un buen ejemplo es “Pegar – Valores”,
uno de los comandos VBA más utilizados. Luego se pasa a una programación VBA más
compleja para buscar soluciones más íntegras.

¿Qué es VBA?

VBA significa Visual Basic for


Applications. Es un lenguaje de
programación que surge de Visual
Basic (VB). Se podría decir que es un
dialecto de VB. VBA de Excel está
adaptado a Excel, para trabajar con
celdas, hojas, autofiltro etc (es decir,
los objetos de la aplicación Excel).

¿Qué puedo hacer con


VBA?

Con este lenguaje de programación


puedes crear tus propios programas en
Excel. Estos programas pueden ser
todo desde una macro (una pequeña
programa VBA, por ejemplo un atajo
personalizado) hasta una aplicación entera con listas desplegables, menús etc...

¿Puedo acceder a VBA?

Sí. VBA está incluido en el Excel ‘normal y corriente’. Se instala con Excel por defecto.

¿Porqué VBA?

VBA sirve para muchas cosas. Imagínate todas las tareas repetitivas que tienes que
ejecutar todos los días. Un ejemplo – siempre vas aplicando el mismo formato a un
grupo de celdas de un libro que te mandan todos los días. En vez de hacer un montón de
clicks para obtener este formato, puedes automatizar el proceso, a un botón, o un atajo
de teclado.

También puedes crear aplicaciones que importan datos desde el libro mayor,
reorganizan los datos, y crean informes personalizados para cada departamento. Casi no
hay límites.

7
VBA de Excel te permite interactuar no solo con otros libros Excel, sino con todos los
programas Office, como Access, Word etc (menos InfoPath que forma parte del Office
2003).

Origen de VBA

Es de Microsoft, y surge de BASIC (Beginner´s All-purpose Symbolic Instruction


Code, o Código de Instrucciones Simbólicas de Uso General para Principiantes), el cual
en su turno es un lenguaje que tiene muchos años ya (desde los años sesenta).

¿Existen varios VBAs?

VBA existe para todas las aplicaciones de Microsoft Office, y estas se llaman ‘host
aplicacions’. Así que hay VBA para Excel, otro para Word etc. Cada VBA se parece al
resto, pero también tienen diferencias, por servir distintos

El editor VBA de Excel


El editor VBA sirve para controlar y manipular tu código VBA, tanto de macros como
de completas aplicaciones VBA y add-ins. Todo parece mucho a Visual Basic, con la
diferencia de que VBA tiene otros objetos (hoja, celda etc)/métodos/eventos.

Contenido de un proyecto

En la columna de izquierda tenemos las piezas que forman parte del proyecto. En este
ejemplo tenemos dos libros abiertos:

Libro1.xls y Personal add-ins.xla (este segundo es un Add-in/Complemento).

Excel Objetos Este Libro y las hojas del libro


Módulos Contenedores para el código del proyecto
Formularios Tus propios formularios, con controles (botones, menús… + código

A la derecha vemos el marcado del Objetos/Módulos/Formularios.

8
VBA bucles Intro

Para qué sirven los bucles

Los bucles sirven para repetir instrucciones varias veces. A lo mejor tienes una columna
en Excel con 25.000 nombres, y quieres sacar las personas cuyos apellidos empieza con
“Lo”. En este caso se puede emplear un bucle que evalúa todos estos nombres según el
criterio “Lo”, uno por uno.

Hay dos tipos generales de bucles:

Bucles Do… Loop


Repite las instrucciones mientras/hasta etc. una condición es TRUE/VERDADERO.

Do While… Loop / While… Wend


Instrucción que repite las instrucciones mientras una condición es
TRUE/VERDADERO.

Ejemplo

Excel tiene valores en las celdas B1:B100. Quieres buscar la primera celda que tenga un
valor más alto/igual que 1,50.

i = 1

Do While Cells(i, 2) <> ""


if Cells(i, 1) >= 1.5 Then Exit Do
i = i + 1
Loop

MsgBox "El valor se encontró en fila no. " & i

9
i = la línea donde empezamos el bucle. Ponemos i = 1. Cells(i, 2) significará línea i
(=1), columna 2. Es decir celda B1. Al final del bucle, i nos dará la línea que buscamos.

Do While Cells(i, 2) <> “” significa que queremos que un bucle siga hasta que no hayan
más celdas con valores en esta columna.

Aplicamos la condición a cada celda, para luego salir del bucle (Exit Do) si encuentra
un valor igual a ó más alto que 1,50 (VBA utiliza punto en vez de coma para
decimales).

Al final devolvemos un Messagebox para presentar el resultado.

Do Until…loop
Instrucción que repite las instrucciones hasta que una condición se convierta en
TRUE/VERDADERO.

Ejemplo

Una hoja Excel tiene datos (en este caso nombres) en las celdas A1:A5. Queremos que
el bucle pare en “Alexis”.

A B
1 Alberto
2 Alejandro
3 Alex
4 Alexis
5 Allain
6

i = 1

Do Until Cells(i, 1) = "Alexis"


i = i + 1
Loop

MsgBox "El nombre Alexis se encontró en la línea " & i

i = la línea donde empezamos el bucle. Ponemos i = 1. Cells(i, 1) significará línea i


(=1), columna 1.

Es decir celda A1. Al final del bucle, i nos dará la línea que buscamos.

Do Until Cells(i, 1) = “Alexis” significa que queremos que un bucle que siga hasta que
encuentre la cadena de texto “Alexis”.

Al final presentamos una caja de diálogo para presentar el resultado, cual en este caso
sería 4.

10
Bucles For… Next
Repite las instrucciones un número especificado de veces.

For i… Next
Esta instrucción se repite el número de veces (i) que tú indicas.

Ejemplo

Creamos un bucle sencillo. Queremos que se repita 4 veces, y que la variable intValor
(al empezar = 1) se incremente con 2 cada vuelta. Este nos da el resultado intValor = 9
(1+2+2+2+2).

Observa que el bucle tiene step 1. Esto significa que i se incrementa con 1 cada vuelta.
Esto es, que si queremos un bucle que vaya para atrás, pondríamos step -1.

intValor = 1

For i = 1 to 4 step 1
intValor = intValor + 2
Next i

For Each… Next


Instrucción que repite las instrucciones según el número de objetos especificados.

Por ejemplo, For each Cell de un rango en Excel.

Ejemplo

En este ejemplo vamos a construir un bucle que evalua cada celda de un rango. El rango
será celdas A1:A5, que se
escribe como Range(Cells(1, 1), Cells(5, 1). Con el Exit For salimos del bucle al
cumplir la condición.

Dim rngArea

rngArea = Range(Cells(1, 1), Cells(5, 1))

For Each Cell In rngArea


If Cell = "Alexis" Then
MsgBox "¡Encontró Alexis"
Exit For
End If
Next

11
VBA Variables
Tipos de variables
Abajo presentamos los más frecuentes tipos de variable de Excel VBA.

Tipo Bytes Descripción Comentario


Byte 1 0-255 Integrales positivos
Boolean 1 True/False Valores discretos
Integer 2 -32.768 hasta + … Integrales
Long (long int.) 4 -2.147.483.648 hasta + … Integrales
Single 4 -3,402823 E38 hasta + … Decimales
Double 8 -1,79769313486232 E308 hasta + … Decimales
Currency 8 15 díg. + 4 decimales Número, 4 dec.
Date 8 1-ene-100 hasta 31-dic-9999 Fechas
Object 4 referencia a objetos Ej. “Workbook”
String 10+ carácteres Ascii (texto) Texto
String (long. fija) 1+ carácteres Ascii, longitud predef. Texto
Variant 16+ cualquier tipo de datos Cubre la mayoría

Declarar variables
¿Porqué declarar variables?

El código saldrá más estructurado


Si no declaras un variable, no sabrás que tipo de datos contendrá.

Es más seguro – evitarás errores tipográficos


VBA te ayudará a poner los nombres correctos. Si no, un error tipográfico puede parar
el programa.

El código trabajará más eficaz


Variables no declaradas serán tratados como Variants, las cuales ocupan mucha más
memoria.

Te ayudará a programar
VBA te ayuda a elegir propiedades/métodos que corresponden a esa variable.

12
Declarar variables

Una variable se declara empleando el comando DIM. DIM significa Dimension, y viene
del antiguo BASIC. Al declarar, puedes indicar el número de dimensiones que la
variable va a tener (ej. guardar números dentro de una variable, en 3 dimensiones).

Para que sea más fácil leer el código, pon un indicador en el nombre de la variable. Así
basta con leer el nombre de la variable para saber de que tipo es. Puede ser str para
String, int para Integer etc.

Una alternativa al DIM es Public. La variable será accesible desde todas partes de tú
proyecto VBA.

Poner nombres explicativos

Intenta poner nombres explicativos a las variables.

Dim strCodigoPostal as String


Dim datFechaRecogida as Date

El nombre puede tener hasta 254 caracteres (por supuesto demasiado…). No puede
empezar con una cifra. Algunos nombres son reservados para VBA/Excel, la cual te
notificará al ejecutar.

¿Donde poner las declaraciones?

VBA te deja declarar casi en cualquier sitio del código. No obstante, la posición puede
dar resultados distintos. Por eso es recomendable seguir unas normas.

Tipo de declaración Ubicación Accesible


Encima del procedimiento (antes Todos los procedimientos del
Dim
del primer Sub) módulo.
Antes de un procedimiento
Dim Ese procedimiento.
específico.
Dim Dentro de un procedimiento. Resto de ese procedimiento.
Encima del procedimiento (antes Todos los procedimientos (de
Public
del primer Sub) todos los módulos).

13
VBA de Excel – ejemplos prácticos de
macros
Una de las utilidades principales de VBA es la de automatizar tareas cotidianas, como
por ejemplo crear un atajo (del teclado) para la función de ‘Pegar como valor’ en Excel.

Estas pequeñas aplicaciones suelen denominarse ‘macros’, pero Excel VBA también
sirve para la programación de aplicaciones más complejas, como servicios de bases de
datos y la manipulación de archivos.

Ejemplos de macros VBA de Excel

Esta lista de ejemplos VBA de Excel recopila algunas pequeñas aplicaciones de código
VBA. Recuerda – haz una copia de seguridad antes de aplicar código VBA a tus
archivos.

Excel y otros programas

Visual Basic – importar datos de Excel


Microsoft Excel es una aplicación muy flexible y permite la comunicación con otros
programas como el Visual Basic. Esto significa que podemos pasar datos entre Excel y
programas como el Visual Basic.

¿Por que pasar datos entre MS Excel y Visual Basic?

En Visual Basic, a veces se utiliza una hoja Excel como una sencilla base de datos, y
por consiguiente tendremos la necesidad de poder abrir este archivo Excel desde la otra
aplicación. A continuación detallamos cómo proceder para establecer contacto entre
Excel y Visual Basic.

Exportar Excel a Visual Basic

Excel permite la exportación de datos a un montón de aplicaciones como de Visual


Basic, bases de datos, XML etc. Es este ejemplo Excel presentamos una solución para
pasar datos desde celdas Excel a una variable Visual Basic.

En concreto vamos a hacer lo siguiente:

• Abrimos un archivo Excel desde VB


• Leemos el contenido del archivo Excel
• Pasamos el contenido Excel a una variable Visual Basic
• Por último Cerramos la hoja de cálculo

14
Configuraciones Excel/Visual Basic

Para que esto funcione, Visual Basic necesitará cargar los objetos de Excel. Por eso, no
olvides marcar Microsoft Excel x.xx Object Library en tu Visual Basic –
Proyecto/Referencias

Código Visual Basic para importar datos Excel


Private Sub LeerExcel()

'dimensiones
Dim xlApp As Excel.Application
Dim xlLibro As Excel.Workbook
Dim xlHoja As Excel.Worksheet
Dim varMatriz As Variant
Dim lngUltimaFila As Long

'abrir programa Excel


Set xlApp = New Excel.Application
'xl.Visible = True

'abrir el archivo Excel


'(archivo en otra carpeta)
Set xlLibro = xlApp.Workbooks.Open _
("c:\Fax2.xls", True, True, , "")

'abrir el archivo Excel


'(archivo en la misma carpeta)
Set xlLibro = xlApp.Workbooks.Open(App.Path & _
"\Fax2.xls", True, True, , "")
Set xlHoja = xlApp.Worksheets("Hoja1")

'1. Si conoces el rango a leer


'varMatriz = xlHoja.Range("A1:C10").Value

'2. Si no conoces el rango


lngUltimaFila = _
Columns("A:A").Range("A65536").End(xlUp).Row

varMatriz = xlHoja.Range(Cells(1, 1), _


Cells(lngUltimaFila, 1))

'utilizamos los datos...


Text1.Text = varMatriz(27, 1)

'cerramos el archivo Excel


xlLibro.Close SaveChanges:=False
xlApp.Quit

'reset variables de los objetos


Set xlHoja = Nothing
Set xlLibro = Nothing
Set xlApp = Nothing

End Sub

15
Importar datos de Word a Excel
Al importar datos a Excel (en este caso texto) de un documento Word podemos aplicar
la función VBA de Create Object. Esta función nos deja ‘conectar’ con los otros
programas Office. De esta manera es bastante sencillo mandar datos entre Excel y el
resto del suite Office de Microsoft.

Este ejemplo de Excel VBA presenta una manera de importar las filas de texto de un
documento Word. El usuario elige desde cual documento Word la importación se va a
realizar, mediante el diálogo Windows predefinido de ‘Abrir’.

Para que esto funcione, no olvides marcar la casilla de Microsoft Word x.xx Object
Library en el menú de ‘Herramientas – Referencias’ del editor VBA.

Option Base 1
Public varText()

Sub abrirWordDesdeExcel()

Dim strWordArchivo As Variant


Dim i, r, intLineas As Integer
Dim appWord As Word.Application
Dim appDoc As Word.Document
Dim rngDoc As Word.Range

'dialogo 'abrir archivo'


strWordArchivo = Application.GetOpenFilename _
("Documentos Word (*.doc), *.doc"): On Error GoTo 99

'crear el objeto Word


Set appWord = CreateObject("Word.Application")
Set appDoc = appWord.Documents.Open(strWordArchivo)

'leer archivo Word


intLineas = appDoc.Paragraphs.Count: ReDim varText(intLineas)

r = 1
For i = 1 To intLineas
Set rngDoc = appDoc.Range( _
Start:=appDoc.Paragraphs(i).Range.Start, _
End:=appDoc.Paragraphs(i).Range.End)
varText(i) = rngDoc.Text
r = r + 1
Next i

'traspasar datos a celdas (o utilizar matriz para otra cosa de VB...)


For x = 1 To UBound(varText)
Cells(x, 1) = varText(x)
'terminar los objetos creados
appDoc.Close: Set appDoc = Nothing
appWord.Quit: Set appWord = Nothing
99:
End Sub

16
Macro para pegar celdas Excel en Word
Esta macro nos deja automatizar el proceso de pegar las celdas Excel seleccionadas, en
un documento nuevo de Word.

Procedimiento

Esta macro debe agregarse a las macros personales, para estar a mano desde cualquier
libro Excel.

Sub Copiar_Excel_a_Word()

'mandar las celdas Excel seleccionadas a nuevo documento Word


'copiar rango selecionado
Selection.Copy

'crear nueva aplicación Word


Dim appWord As Word.Application
Set appWord = New Word.Application

With appWord
.Visible = True
.Activate
End With

'crear nuevo documento Word


appWord.Documents.Add

'pegar celdas Excel


appWord.Selection.Paste

'liberar el objeto Word


Set appWord = Nothing

End Sub

Libros y hojas Excel


Cerrar libro Excel (guardar cambios)
ActiveWorkbook.Close
ActiveWorkbook.Close Savechanges:=True
ActiveWorkbook.Close(True)

Cerrar libro Excel (sin guardar cambios)


ActiveWorkbook.Close(False)
ActiveWorkbook.Close Savechanges:=False

17
Cerrar libro Excel (variable, sin guardar cambios)
Application.DisplayAlerts = False
Windows(Libro_mayor).Close
Application.DisplayAlerts = True

Abrir libro Excel ( Ruta fija)


Workbooks.Open FileName:="C:\Trabajo\Informe.xls"

Abrir libro Excel (diálogo)


Msg = MsgBox("Elija archivo para abrir.", vbOKOnly, (""))

strArchivo = Application.GetOpenFilename
On Error GoTo 99

Workbooks.OpenText Filename: = strArchivo


If strArchivo = "" Then Exit Sub
strArchivo = ActiveWindow.Caption
99:
Exit sub

Devolver nombre del libro Excel


strNombre = ActiveSheet.Parent.FullName
MsgBox ActiveWorkbook.FullName

Nombre de la hoja (variable)


'asigna nombre variable a la hoja a variable
strHoja = ActiveWindow.Caption
Windows(strHoja).Activate 'para activar el libro del nombre asignado

Insertar hoja nueva (elegir posición)


ActiveWorkbook.Sheets.Add Before:=Worksheets("Informe1")

Insertar hoja nueva (primera posición)


Sheets("Informe1").Copy After:=Worksheets(Worksheets.Count)

Mover hoja
Worksheets("informe5").Move After:=Worksheets("Informe4")

Ordenar hojas (orden alfabético)


intNumeroHojas = ActiveWorkbook.Worksheets.Count
For i = 1 To intNumeroHojas
For j = i To intNumeroHojas
If LCase(Worksheets(j).Name) < LCase(Worksheets(i).Name) Then
Worksheets(j).Move Before:=Worksheets(i)
End If
Next j
Next i

18
Suprimir una hoja determinada
Application.DisplayAlerts = False

For i = 1 To Sheets.Count
Sheets(i).Activate
xxx = ActiveCell.Worksheet.Name
If xxx = "Informe" Then
ActiveWindow.SelectedSheets.Delete
End If
Next

Application.DisplayAlerts = True

Seleccionar primera hoja


ActiveWindow.ScrollWorkbookTabs Position:=xlFirst

Seleccionar última hoja


ActiveWindow.ScrollWorkbookTabs Position:=xlLast

Formatos Excel y VBA


Excel pone a disposición un montón de formatos. Abajo presentamos como modificar
algunos de ellos a través de macros Excel VBA.

Redondear celdas
Set Area = Selection
For Each Cell In Area
z = Round(Cell, 2)
Cell.Value = z
Cell.NumberFormat = "#,##0.00"
Next Cell

Formatear fuente
Cells.Select
With Selection.Font
.Name = "MS Sans Serif"
.Size = 10
End With

Líneas de división
ActiveWindow.DisplayGridlines = False

Indice de colores
ActiveWorkbook.Colors(44) = RGB(236, 235, 194) 'verde

Colorear rango
Range("A1:B10").Interior.ColorIndex = 44

19
Cambiar entre estilos A1 / RC
Application.ReferenceStyle = xlA1Application.ReferenceStyle = xlR1C1

Letra Negrita
Selection.Font.Bold = True

Letra Cursiva
Selection.Font.Italic = True

Letra Subrayada
Selection.Font.Underline = True

Filas Excel – macros VBA


Encontrar última fila
intUltimaFila = _
Columns("A:A").Range("A65536").End(xlUp).Row

Encontrar última fila


intUltimaFila = _
ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count

Encontrar última fila


MaxRow = Cells.SpecialCells(xlLastCell).Row
MaxCol = Cells.SpecialCells(xlLastCell).Column

Encontrar última celda (buscar al revés)


Dim lngUltimaCelda As Long
If WorksheetFunction.CountA(Cells) > 0 Then
lngUltimaCelda = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
MsgBox lngUltimaCelda
End If

Encontrar última fila (en columna especificada)


Dim intUltimaFila As Range

If WorksheetFunction.CountA(Columns(1)) > 0 Then


Set intUltimaFila = Range("65536").End(xlUp)
MsgBox intUltimaFila.Address
End If

Suprimir filas vacías


intLastRow = Columns("A:A").Range("A65536").End(xlUp).Row
For r = intLastRow To 1 Step -1
If Application.CountA(Rows(r)) = 0 Then Rows(r).Delete

20
Next r

Suprimir filas vacías


Dim intNumDeFilas As Long

Selection.SpecialCells(xlCellTypeLastCell).Select
intNumDeFilas = Selection.Row
For i = 1 To intNumDeFilas
If Application.WorksheetFunction.CountA(Rows(i)) = 0 Then
Rows(i).Delete
End If
Next

Suprimir filas vacías


intUltimaFila = _
ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
For r = intUltimaFila To 1 Step -1
If Application.CountA(Rows(r)) = 0 Then Rows(r).Delete
Next r

Suprimir filas por condición


Dim rngString As Range

Do
Set rngString = Cells.Find("Aglis", MatchCase:=False, _
LookAt:=xlPart, LookIn:=xlValues)
If Not rngString Is Nothing Then
rngString.EntireRow.Delete
End If
Loop Until rngString Is Nothing

Suprimir filas vacías por dos condiciónes X, Y


For i = intUltimaFila To 1 Step -1
Let strTest= Application.Cells(i, 2)
If strTest <> "X" And strTest <> "Y" Then Rows(i).Delete
Next i

Insertar fila
Selection.EntireRow.Insert

Insertar columna
Selection.EntireColumn.Insert

Eliminar fila
Selection.EntireRow.Delete

Eliminar columna
Selection.EntireColumn.Delete

21
Ordenar Ascendente
Selection.Sort key1:=Range(“A1”), Order1:=xlAscending,_
Header:=xlGuess, OrderCustom:=1; MatchCase:=False,_
Orientation:=xlTopToBottom

Ordenar Descendente
Selection.Sort key1:=Range(“A1”), Order1:=xlDescending,_
Header:=xlGuess, OrderCustom:=1; MatchCase:=False,_
Orientation:=xlTopToBottom

Buscar
Cells.Find( What:=”Ramon”, Afetr:=ActiveCell, LookIn:=xlFormulas,
LookAt:=clPart, SearchOrder:=xlByRows, SearchDirection:=xlNext,
MatchCase:=false ).Active

Columnas de Excel y VBA


Presentamos unas macros para trabajar con columnas Excel desde Excel VBA.

Encontrar última columna (buscar al revés)


Sub EncontrarUltimaColumna()
Dim intUltimaCol As Integer

If WorksheetFunction.CountA(Cells) > 0 Then


intUltimaCol = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
MsgBox intUltimaCol
End If
End Sub

Encontrar última columna (en fila especificada)


Sub EncontrarUltimaColumna()
Dim intUltimaCol As Range

If WorksheetFunction.CountA(Rows(1)) > 0 Then


Set intUltimaCol = Range("IV1").End(xlToLeft)
MsgBox intUltimaCol.Address
End If
End Sub

Suprimir columnas vacías en el rango


Sub SuprimirColumnas()
Dim cCount As Integer, c As Integer
Dim DeleteRange as Range

DeleteRange =("A1:B10")

If DeleteRange Is Nothing Then Exit Sub

22
'Ejemplo: DeleteEmptyColumns Range("A1:Z1")
If DeleteRange.Areas.Count > 1 Then Exit Sub

With DeleteRange
cCount = .Columns.Count
For c = cCount To 1 Step -1
If Application.CountA(.Columns(c)) = 0 _
Then .Columns(c).EntireColumn.Delete
Next c
End With
End Sub

Suprimir cada n-columnas


Sub SuprimirColumnas()
Dim rCount As Long, r As Long
Dim DeleteRange as range

DeleteRange =("A1:B10")

If DeleteRange Is Nothing Then Exit Sub


If DeleteRange.Areas.Count > 1 Then Exit Sub
If n < 2 Then Exit Sub

With DeleteRange
cCount = .Columns.Count
For c = n To cCount Step n - 1
Columns(c).EntireColumn.Delete
Next c
End With
End Sub

Excel VBA y la paleta de colores


Excel emplea una paleta de 56 colores predefinidos. Puedes cambiar estos colores desde
Herramientas – Opciones – Color o desde código VBA. Abajo presentamos unos
ejemplos de código VBA para modificar la paleta de colores del libro Excel.

Por desgracia, a muchos de nosotros los colores de la hoja Excel predefinidos por
Microsoft parecen bastante fuertes, y a veces hacen que la hoja sea difícil de leer.

Los colores forman parte del diseño del libro, son importantes para una buena
presentación de un informe. Pero por regla general tampoco se debe pasar utilizando
demasiado color.

Excel y Colores RGB

Excel expresa colores del formato RGB (Red, Green, Blue). Red, Green, Blue son
variables cuales expresan el grado de estos colores, valores entre 1 y 255. También
podemos expresar el color en formato HEX (hexadecimal).

23
Cambiar colores de la paleta Excel

Entonces, ¿qué podemos hacer para que Excel siempre tenga los colores definidos por
ti? Una solución sería crear una plantilla con nuestros formatos. Excel llamará esta
plantilla al crear un libro nuevo.

Otra solución es crear una macro cual nosotros podemos llamar cuando nos convenga.
Esto nos da un poco más de control. En este ejemplo cambiaremos los colores 40 y 41
(de los 56) de la paleta.

ActiveWorkbook.Colors(40) = RGB(234, 234, 234)


ActiveWorkbook.Colors(41) = RGB(236, 235, 194)

Código VBA para cambiar colores de celdas Excel

Para cambiar los colores aplicados a una celda ejecutamos una de las siguientes
instrucciones.

Selection.Interior.ColorIndex = 40
Selection.Interior.ColorIndex = _
xlNone/xlColorIndexAutomatic/xlColorIndexNone
Selection.Interior.Color = RGB(234, 234, 234)
Selection.Interior.Color = ?000066? 'hexadecimal

Resetear paleta de colores

Para resetear los colores a los predefinidos de Excel, aplicamos el método ResetColors.

ActiveWorkbook.ResetColors

Copiar colores de otro libro Excel

También se puede copiar (importar) la paleta de otro libro Excel. Para esto cambiamos
la propiedad Colors del libro.

ActiveWorkbook.Colors = Workbooks("C:\MiLibroDeColores.xls").Colors

Devolver colores del libro Excel actual

A lo mejor nos interesa saber que color tiene una celda. La propiedad ColorIndex nos
ayuda.

i = Cells(1, 1).Interior.ColorIndex
MsgBox i

Aplicar colores por condiciones en Excel VBA

Podemos colorear celdas por condiciones, evaluando una cadena de texto, por ejemplo.

For Each Item In Intersect(ActiveSheet.UsedRange, Selection.Cells)


If Item.Text = "ColaCao" Then

24
Item.Interior.ColorIndex = 44
End If
Next

Colorear celdas Excel al hacer click


Este trocito de código VBA Excel colorear
celdas al hacer click sobre ellos. Es una macro
que utiliza el evento
Worksheet_SelectionChange de las hojas de
libro Excel.

Por eso hay que incluir este código en los


objetos de las hojas. En ejemplo abajo habría
que poner el código en los contenedores de
código de una o más de los objetos Hoja1,
Hoja2 y Hoja3.

Para colorear solo la celda activa


Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Interior.ColorIndex = 3
End Sub

Para colorear todas las celdas seleccionadas


Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Target.Interior.ColorIndex = 3
End Sub

25
VBA para proteger hojas de un libro
Excel
Con la ayuda de un truco de VBA de Excel puedes permitir que el usuario solo pueda
abrir por ejemplo la primera hoja (sin palabra de paso) – pero no las otras (cuales
requieren palabra de paso). Esta función no está integrada en Excel
(sorprendentemente), por eso hay que recurrir a VBA.

Eventos empleados para la protección

Para esto vamos a utilizar el evento Workbook_SheetActivate, un evento que salta cada
vez que alguna hoja se active. Es decir, el evento se activará cuando el usuario hace
click sobre una etiqueta de una hoja. Si la hoja forma parte de las restringidas, Excel
pedirá palabra de paso. Al introducir una palabra de paso errónea, se queda en la hoja
anterior.

Grado de seguridad de la macro para proteger hojas

Cualquier persona puede entrar al código VBA para ver la palabra de paso. Por eso
debes proteger el código (VBA editor – Click derecho sobre EsteLibro – Propiedades).

Este método no da 100% de seguridad. Si activamos la protección de los módulos VBA


tenemos bastante seguridad, pero hay que tener en cuenta que existen varios programas
comerciales para resolver el tema de palabras de paso de Excel.

Los procedimientos

Pon este código en el contenedor ‘EsteLibro‘ del editor VBA (Herramientas – Macro –
Editor VBA).

Luego tienes que poner que hojas/palabra de paso (ver ‘Preparar modelo‘ del código).

Código VBA para proteger hojas Excel


Dim strStartHoja As String
Dim strSegundaHoja As String
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim z As Integer
Dim i As Integer
Dim x As Boolean
Dim varHoja As Variant
Dim varPaso As Variant
Dim varInput As Variant

'preparar modelo [admin. input]


varHoja = Array("Sheet2", "Sheet3") 'las hojas a proteger...
varPaso = "gofio" 'palabra de paso... [letras/números]

'desconectar otros Events (evitar un tipo de bucle)


Application.EnableEvents = False

26
'comprobar hojas
strSegundaHoja = Sh.Name
For i = LBound(varHoja) To UBound(varHoja)
If varHoja(i) = strSegundaHoja Then x = True
Next i
If x = False Then GoTo 99

'ocultar la hoja temporalmente


z = ActiveWindow.Index
Windows(z).Visible = False

'comparar palabra de paso


varInput = InputBox("Palabra de paso:")
If varInput <> varPaso Then Sheets(strStartHoja).Select

'volver a mostrar la hoja


Windows(z).Visible = True

99:

'conectar Events
Application.EnableEvents = True

End Sub

'*************************************************

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)


'recordar hoja inicial
strStartHoja = Sh.Name
End Sub

Crear enlaces a las hojas Excel


Si nuestro libro Excel contiene muchas hojas (hasta 256) convendría hacer una lista de
enlaces a cada hoja. Esto puede ayudar mucho a los ‘navegantes’ de nuestros libros.

Y como siempre, esta lista se puede crear manualmente. O se puede recurrir a una
macro de VBA, cual tardará al máximo un par de segundos para concluir el trabajo.

Procedimiento

Empezamos con un libro Excel cualquier, pero que tenga por lo menos dos hojas. Luego
vamos a crear un módulo dentro de este libro. En este módulo escribimos el código.

Sub Links_hojas()

Dim wrbLibro As Workbook


Dim wrsHojaActiva As Worksheet, wsHoja As Worksheet
Dim intFila, intColumna As Integer

Set wrbLibro = ActiveWorkbook


Set wrsHojaActiva = ActiveSheet

27
'en que fila/columna empezar la lista
intFila = 4
intColumna = 1

'el bucle repasa todas las hojas


For Each wsHoja In wrbLibro.Worksheets

'para excluir hoja de los links


If wsHoja.Name = "Hoja4" Then GoTo ProxHoja

'crear links
If wsHoja.Name <> wrsHojaActiva.Name Then

wrsHojaActiva.HyperLinks.Add wrsHojaActiva.Cells(intFila, intColumna),


_
"", SubAddress:="'" & wsHoja.Name & "'!A1", TextToDisplay:=wsHoja.Name

intFila = intFila + 1
End If

ProxHoja:
Next wsHoja

End Sub

Abrir otro libro de Excel utilizando VBA

Este código sirve para abrir otro libro Excel a través del diálogo ‘Abrir’. Allí el usuario
elige el libro a abrir. Si el usuario pulsa Cancelar, el diálogo se cierra.

Este procedimiento en sí no sirve para mucho (porque luego se debe hacer algo con este
libro, verdad), pero al final será un procedimiento básico en muchos de tus futuros
programas de Excel VBA.

Sub Abrir_archivo()

Dim strRutaArchivo As String

'un poco de información


MsgBox ("Abra el archivo Excel.")

'elegir archivo
strRutaArchivo = _
Application.GetOpenFilename("Libro de Microsoft Excel (*.xls), *.xls")

28
'abrir archivo
On Error GoTo 9
Workbooks.Open Filename:=strRutaArchivo
9:

End Sub

Messagebox y Excel VBA


Las messagebox son muy útiles (y fáciles de usar), y crea una interfaz entre el usuario y
el programa. Sirven para

• Mostrar información al usuario


• Recibir información del usuario
• Devolver información del usuario

Construcción sintáctica de la messagebox


Msgbox "Mensaje", Botones/íconos, "Título"

o en el caso de devolver información

Respuesta = Msgbox("Mensaje", Botones/íconos, "Título")

Nota las paréntesis en la segunda construcción.

Mensaje

Cualquier tipo de texto. Para crear un salto de línea empleamos el carácter vbCrLf.

Actualización terminada:" & vbCrLf & "- Importación de datos de venta.

Botones

Si quieres puedes añadir cualquier de estos cuatro botones (si no pones nada Excel te
pondrá vbOkOnly por defecto).

vbOkOnly
vbOkCancel
vbYesNoCancel
vbAbortRetryIgnore

29
Iconos

Puedes elegir entre los siguientes.

vbCritical
vbQuestion
vbExclamation
vbInformation

Título

Cualquier texto.

Devolver información

Si quieres que el programa utilice la respuesta del usuario, estas son las cifras que te
devuelve.

Ok = 1
Cancel = 2
Abort = 3
Retry = 4
Ignore = 5
Yes = 6
No = 7

Ejemplos

Te ponemos unos ejemplos módelo para que te vayas acostumbrando a las diferentes
messagebox.

Sub MessageBox()
msgbox "Actualización terminada:", _
vbOKOnly, "Información"
End Sub

Sub MessageBox()
msgbox "¿Quieres seguir?", vbYesNo, "Información importante"
End Sub

30
Sub MessageBox()
Dim intRespuesta As Integer
intRespuesta = MsgBox("¿Quieres seguir?", vbQuestion + vbYesNo, _
Información importante")
If intRespuesta = 6 Then
MsgBox"Seguimos"
Else
MsgBox"Terminamos"
End If
End Sub

Sub MessageBox()
msgbox "Actualización terminada:" & _
vbCrLf & vbCrLf & _
"- Importación de datos de venta." & vbCrLf & _
"- Cálculos de impuestos." & vbCrLf & _
"- Venta por proveedor." & vbCrLf _
, vbOKOnly, "Actualización terminada."
End Sub

Sub MessageBox()
msgbox "Actualización terminada:" & vbCrLf & vbCrLf & _
"- Importación de datos de venta." & vbCrLf & _
"- Cálculos de impuestos." & vbCrLf & _
"- Venta por proveedor." & vbCrLf _

31
, vbExclamation + vbOKOnly, _
"Actualización terminada."
End Sub

Sumar rangos variables con VBA Excel


Sumar un rango en Excel es fácil. Sumar un rango expresado por una variable en VBA
es un poco más complicado (pero sigue siendo fácil).

No siempre se sabe de antemano que celdas formarán parte del rango a sumar. Entonces
tenemos que expresar el rango de forma variable.

En Excel es fácil sumar este rango mediante una sencilla fórmula. Pero VBA no
contiene ninguna función igual. Entonces hay que hacer que VBA utilice las funciones
de Excel.

Utilizar funciones Excel en VBA

Tenemos un rango varSuma, el rango a sumar. Para sumar las celdas de este rango
tenemos que llamar a la función SUM de Excel.

Application.WorksheetFunction.Sum(varSuma)

De esta manera puedes aplicar cualquier fórmula de Excel en VBA, con tal de que
empieces la línea de código con

Application.WorksheetFunction...

Nuestro ejemplo

En este ejemplo el rango que nos interesa sumar son los valores correspondientes a
“BB”, es decir C8:C13.

32
Escribir la suma (en celda)
'el rango a sumar
varSuma = Range(Cells(8, 3), Cells(13, 3))
'sumar el rango
Cells(1, 1) = Application.WorksheetFunction.Sum(varSuma)

<h2>Escribir la suma (variable)</h2>


<div class="cb">
<pre>

'el rango a sumar


varSuma = Range(Cells(8, 3), Cells(13, 3))
'sumar el rango
SUMA = Application.WorksheetFunction.Sum(varSuma)

33
DOCUMENTACIÓN EN INGLÉS
Obtenido desde la dirección : http://www.excel-vba.com/excel-vba-contents.htm

Application is a VBA object, IT IS EXCEL. For example: Application.Quit will


close Excel all together.

Exercise 1a

Step 1: Open a new workbook in Excel and use the ALT/F11 keys to go to the
visual basic editor (VBE).

Step 2: Copy the following macro in the code window of any sheet. As you can
read, you are asking Excel to close itself.

Sub testLesson13a1()

Application.Quit

End Sub

Step 3: As you have learned in lesson 7, go to Excel and run the macro from
the menu bar (Excel before 2007) or the ribbon (Excel since 2007).

Step 4: You will be asked if you want to save the workbook. Answer "No" and
Excel will close itself.

Exercise 1b

If you do not want to be bothered by the alert to save your workbook you will
add a line of code to the small macro: ActiveWorkbook.Saved = True

Step 1: Open a new workbook in Excel and use the ALT/F11 keys to go to the
visual basic editor (VBE).

Step 2: Copy the following macro in the code window of any sheet. As you can
read, you are asking Excel to close itself but saying first that the workbook has
already been saved.

Sub testLesson13a1()

ActiveWorkbook.Saved = True
Application.Quit

End Sub

Step 3: Run the macro from Excel as you did with the previous one.

34
Excel will just close itself without asking you anything.

There is a word that you can use with Application that will neutralise all the
alerts that Excel can send your way. Discover this word and many others that
you can use in combination with Application in the downloadable tutorial on
Excel macros.

There are many other words that you can use in combination with Application.
Among them, two important words are:

ScreenUpdating (Application.ScreenUpdating)
When you do not want to see your screen follow the actions of your VBA
procedure (macro), you start and end your code with the following sentences:
Application.ScreenUpdating = False
Then at the end:
Application.ScreenUpdating = True

Exercise

Step 1: Open a new workbook in Excel and use the ALT/F11 keys to go to the
visual basic editor (VBE).

Step 2: Copy the following macro in the code window of any sheet. As you can
read: starting in cell A1 a value of "99" will be entered in the selected cell then
the cursor will move one cell down to enter "99", repeat the process until the
row number of the selected cell is 3000 and come back to cell A1.

Sub testLesson13b1()

Range("A1").Select

Do Until Selection.Row = 3000


Selection.Value = 99
Selection.Offset(1, 0).Select
Loop

Range("A1").Select

End Sub

Step 3: Run the macro from Excel as you did with the previous one.

Step 4: Remove all the "99" from the cells

Step 5: Copy the following macro in the code window of a new workbook and
run it. Two lines of code have been added to the previous macro to prevent all
the steps of the action to be seen on the screen.

Sub testLesson13b2()

35
Application.ScreenUpdating = False

Range("A1").Select

Do Until Selection.Row = 3000


Selection.Value = 99
Selection.Offset(1, 0).Select
Loop

Range("A1").Select

Application.ScreenUpdating = True

End Sub

Step 6: Run the macro from Excel as you did with the previous one. You will
see a blank sheet, no movement whatsoever and then a sheet where cells A1
to A3000 are equal to "99".

Sometimes you or the users might want to see the action. Some other times
you or the user do not want to see the action. It is up to you to use the sentence
or not.

You can even use the pair of sentences (as below) anywhere within a long
macro to refresh the screen at significant points in the process. With the pair of
sentences you call for a refreshment with Application.ScreenUpdating = True
and then interrupt the refreshment process until the next refreshment with
Application.ScreenUpdating = False. Before the end of the macro you will
use a final Application.ScreenUpdating = True.

The pair of refreshing sentences:


Application.ScreenUpdating = True
Application.ScreenUpdating = False

Step 7: Close the workbook without saving anything

To develop a VBA procedure that is triggered by an event relating to the


workbook (when you open it, when you save it, when you close it) see the VBA
lesson on events.

ThisWorkbook

ThisWorkbook is the workbook within which your VBA procedure runs. So if


you write:
ThisWorkbook.Save
The workbook within which your VBA procedure (macro) runs will be saved.

If you want to close the workbook within which your VBA procedure (macro)
runs without saving it you will write these two lines of code:

36
ThisWorkbook.Saved=True
ThisWorkbook.Close

Workbooks and Windows

When you work with two workbooks you will move from one to the other with:
ThisWorkbook.Activate
Windows("theOtherWorkbookName.xls").Activate

Sheets

You access a worksheet named " Balance" with:


Sheets("Balance").Select
Note that the word "Sheets" is plural and always use the quotes within the
parenthesis

You cannot select a sheet that is hidden so you will need to write:
Sheets("Balance").Visible= True
Sheets("Balance").Select
and then if you want to hide the sheet again:
Sheets("Balance").Visible= False

The name of a sheet must not have more than 31 characters and should not
include certain special characters like " ? : \ / [ ]" . If you do not respect
these rules your procedure will crash.

The following lines of code will generate an error message:


Sheets("Sheet1").Name= "Balance and Introduction to Numbers" because
there are more than 31 characters including the spaces
Sheets("Sheet1").Name= " Balance: Introduction" because of the special
character :
Sheets("Sheet1" ).Name= " " because the name cannot be blank

You can not go directly from a sheet to a cell on another sheet. For example if
the active sheet is "Balance" and you want tot go to cell A1 of a sheet named "
Results" you cannot write:
Sheets("Results").Range("A1").Select
You must take two steps:
Sheets("Results").Select
Range("A1").Select

Cells, Ranges, Columns and Rows in VBA for Excel

A lot of VBA beginners start their career using Cells. For example:
Cells(1,1).Select is the same thing as Range("A1").Select and
Cells(11,31).Select is the same as Range("AE11").Select.

37
We strongly recommend that you use Range instead of Cells to work with cells
and groups of cells. It makes your sentences much clearer and you are not
forced to remember that column AE is column 31.

The only time that you will use Cells is when you want to select all the cells of a
worksheet. For example:
Cells.Select
To select all cells and then to empty all cells of values or formulas you will use:
Cells.ClearContents

Range

To select a single cell you will write:


Range("A1").Select

To select a set of contiguous cells you will use the colon and write:
Range("A1:G5").Select

To select a set of non contiguous cells you will use the comma and write:
Range("A1,A5,B4").Select

To select a set of non contiguous cells and a range you will use both the colon
and the comma:
Range("A1,A5,B4:B8").Select

Offset

The Offset property is the one that you will use the most with Range to move
around the sheet.

To move one cell down (from B2 to B3): Range("B2").Offset(1,0).Select


To move one cell to the right (from B2 to C2): Range("B2").Offset(0,1).Select
To move one cell up (from B2 to B1): Range("B2").Offset(-1,0).Select
To move one cell to the left (from B2 to A2): Range("B2").Offset(0,-1).Select

To move one cell down from the selected cell:


ActiveCell.Offset(1,0).Select

As you notice the first argument between the parentheses for Offset is the
number of rows and the second one is the number of columns. So to move from
A1 to G6 you will need:
Range("A1").Offset(5,6).Select

You will use very often the following piece of code . It selects a cell and 4 more
to the right to be copied/pasted somewhere else:
Range(ActiveCell,ActiveCell.Offset(0,4)).Copy
Notice the comma after the first ActiveCell and the double closing parentheses
before the Copy

38
Deactivating filters

When you work in an Excel database you might want to make sure that all data
filters are off. To this end you will start your procedure with two "If"statements.
For example with a database starting in cell A1 here are the two sentences:

Range("A1" ).Select
If ActiveSheet.AutoFilterMode = True Then Selection.AutoFilter

If ActiveSheet.FilterMode = True Then ActiveSheet.ShowAllData

Sorting Data

Here is a simplified Excel macro to sort data using criteria in three different
fields. The following Excel macro will work with any size database starting in cell
A1 and it will work in any version of Excel (1997 to 2010).

Sub proFilter()

Range("A1").Sort Key1:=Range("A2"), Order1:=xlAscending,


Key2:=Range( _
"B2"), Order2:=xlAscending, Key3:=Range("C2"),
Order3:=xlAscending, _
Header:=xlYes

End Sub

The code above is much simpler than the following recorded macro in Excel
2007. This recorded macro will not work in earlier versions of Excel (1997 to
2006).

ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add
Key:=Range("A2:A7"), _
SortOn:=xlSortOnValues, Order:=xlAscending,
DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add
Key:=Range("B2:B7"), _
SortOn:=xlSortOnValues, Order:=xlAscending,
DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add
Key:=Range("C2:C7"), _
SortOn:=xlSortOnValues, Order:=xlAscending,
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:E7")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin

39
.Apply
End With

Forms (Userforms) in VBA for Excel

When the message box or the input box are not sufficient any more to
communicate with the user you need to start developing userforms.

The form is used to require information from the user to feed the VBA
procedure. Different basic controls can be added to the userform they are
called: labels, text boxes, combo boxes, list boxes, check boxes, option
buttons, frames, command buttons, spin buttons and images . To learn
more about all the controls see lessons 26 to 33.

Creating a Userform in Excel

Userforms are created in the Project Window of the Visual Basic Editor. You
will also find the toolbox that allows you to add controls to your userforms in the
Visual Basic Editor.

In the Visual Basic Editor you right click in the project window and you will see
this menu appear:

Go to "Insert" and select "UserForm". You will then see the following:

40
On the right you see the userform that you have just added to your workbook.
On the left is the toolbox with all the controls that you can add to your userform.
You can hide that toolbox by clicking on the "X" and bring it back by clicking on
the toolbox icon or by going to the menu bar "View/Toolbox". We will use
the toolbox later in this section.

Userforms Properties and VBA Code

In this lesson we will review some of the properties of the userform, we will
develop some programming to call the userform and some other programming
within the userform itself.

Userforms Properties

When you double click on the userform name in the project window of the
Visual Basic Editor the properties windows shows 35 properties of the userform.
On this website we will work with two of them. For the other 33 properties see
the downloadable tutorial on Excel macros (VBA)

41
VBA Code within the UserForm

In lesson 9 you have learned about events. The events trigger the macros.
There are many events that happen around the userform. For example, a macro
can start when the userform is shown (or activated) and another macro can
start when a user clicks on a command button. You will learn all these two
events in the downloadable tutorial on Excel macros.

Labels in VBA for Excel

In the toolbox the label has this icon . The label is a passive control
meaning that the user never really acts on it. It is there to inform the user and to
label other controls like text boxes, combo boxes or list boxes.

Properties

Among the properties of the label is:

- WordWrap: If you want to write more than one line of text in a label set this
property to "True" .

Adding a Label to a Userform

42
To add a label to a userform you left click on its icon in the toolbox. You move
the cursor to the userform, you click again and the label appears. You can then
resize it to your liking. If you double click on the label icon in the toolbox you
can then click on the form as many times as you need labels. When you are
finished adding labels just click once on the label icon of the toolbox.

Text Boxes in VBA for Excel

In the toolbox the text box icon is: .

The text box is the simplest control that requires an entry by the user. The user
types something in it and this value can then be used in your VBA procedure.
You will usually add a label to accompany the text box.

For most controls including the VBA for Excel text box there are general
properties that allow you to set the font, the color of the font, the color of the
background, the type of background, the type of border and other design
features.

As its name says it the text box carries text. To use the contents of a text box as
a number, to add dollar signs, decimal and other numerical features see the
downloadable tutorial on Excel macros (VBA).

Adding a Text Box to a Userform

To add a text box to a userform you left click on its icon in the toolbox. You
move the cursor to the userform, you click again and the text box appears. You
can then resize it to your liking. If you double click on the text box icon in the
toolbox you can then click on the form as many times as you need text boxes.
When you are finished adding text boxes just click once on the text box icon of
the toolbox.

Command Buttons in VBA for Excel

In the toolbox the command button has this icon . The command button is
a very active control and there is always VBA code behind it.

The command buttons are usually placed at the bottom of the form and serve to
complete the transaction for which the form has been created. The caption of
these buttons are usually "Go" , "Run" , "Submit" , "Cancel" , etc.

Properties

Among the other properties of the command button are:

- WordWrap to be able to write more that one line on a button,


- ControlTipText which generates a small comment box when the user moves
the mouse over the control. You can use this property to give explanations and
instructions about the command button,

43
Adding a Command Button to a Userform

To add a command button to a userform you left click on its icon in the toolbox.
You move the cursor to the userform, you click again and the command
button appears. You can then resize it to your liking. If you double click on the
command button icon in the toolbox you can then click on the form as many
times as you need command buttons. When you are finished adding command
buttons just click once on the command button icon of the toolbox.

VBA Code

Most of the VBA code (VBA sentences) is created within the command button
when you develop simple userforms. Here are two exercises creating VBA code
within the command button.

Combo Boxes in VBA for Excel

Before we begin on the Combo Box

The difference between a combo box and a list box is that the combo box is a
drop-down list and the user can submit a single value from the drop-down list.
The list box shows a certain number of values with or without a scroll bar and
the user can select one or more values.

Combo Box List Box

If you are looking for a drop-down list (also called pull-down lists) to use on a
regular worksheet see the much easier and user friendly Excel drop-down
lists in the website on Excel.

When you double click on the combo box in the Visual Basic Editor you will
see all its properties in the Properties window .

No programming is needed to submit the list of values that will be offered to the
user within the combo box. Look for the RowSource property.

The RowSource Property:

The values that should appear in the drop-down list of the combo box are
submitted in the RowSource property. For example, if the value of the
RowSource property is Balance!A1:A12 The values residing in cell A1 to A12

44
of the sheet named Balance will be offered as choices to the user who clicks on
the small arrow of the combo box.

The rules to submit the RowSource property is the name of the sheet where
the list resides followed by an exclamation point (!), the address of the first
cell, a colon and the address of the last cell.

IMPORTANT NOTE: if there is a space or a special character within the name


of the sheet where the list resides you must surround the name of the
sheet with simple quotes. For example: 'New Balance'!A1:A12.

Option Buttons, Check Boxes and Frames

In the toolbox the option button has this icon , the check box has this one
and, the frame this one .

You do not need to add a label to accompany the check box or the option
button because they come with their own.

The check boxes and the option buttons are both used to offer the user a
choice. The main difference between check boxes and option buttons is that if
you have 5 of each on a form a user can check all 5 check boxes but can only
select one of the option buttons.

If you want to create two sets of option buttons read below on frames and
option buttons. If you do not want to use frames to create groups of option
buttons you will need to use the "GroupName" property of the option buttons. All
option buttons with the same GroupName work together.

Properties

- WordWrap to be able to write more that one line in the caption,


- ControlTipText which generates a small comment box when the user moves
the mouse over the control. You can use this property to give explanations and
instructions about the option button or the check box.
- Enabled and Visible are properties that you can change programmatically to
disable or render invisible an option button or a check box following a previous
selection in another control of the userform.

Frames

Frames are also a passive control. Frames are used to improve the layout of
the userform. You can use them around a group of controls that have
something in common.

Frames become more important to manage option buttons. If you have two sets
of option buttons on a userform and you do not place them within a frame they
all work together and you can choose only one. If you put each set within a
frame you can choose one in each set.

45
When you move a frame all its controls move with it.

Excel Spin Buttons

Spin Button

In the toolbox the spin button has this icon .

You can ask a user to enter a value directly in a text box but you can make
things a little more attaractive by using a text box and a spin button.

The spin button is not really used by itself. Because the spin button does not
show its value it is usually used with a text box. The text box shows a number
and by clicking on the arrows of the spin button the value in the text box is
increased (or decreased) by 1, or 5 or 10...by whatever value that is set within
the properties of the spin button.

Properties

Among the other properties of the spin buttons are:

- Min is the minimum value of the spin button. It can be negative


- Max is the maximum value of the spin button. It can be negative
- Small is the value of the change when the user clicks on the arrows
- Large is the value of the change when the user clicks on the scroll bar of the
spin button.

Excel Image Controls

Image Control

There is a control in the toolbox called "Image" . Within this control you can
show all types of pictures. You set an image control on a userform and you
submit a picture in the property "Picture" . The picture becomes part of the
control and userform.

Fitting the Picture

The first thing that you want to do is to fit the picture in the image control to
make the size of the control adapt to the size of the picture.

When you are in the Visual Basic Editor and you single click on an image
control a frame appears around it with 8 stretchers (picture below). If you double
click on the middle stretcher (when a two tips arrow shows) of the right side or
on the middle one at the bottom or on the bottom right corner stretcher the
image control will adapt to the size of the image. Double clicking anywhere else
will take you to the VBA code and will not adapt the control size to the picture
size.

46
PictureSizeMode Property

Another property of the image control is the PictureSizeMode.

If the property is set to the default value 0-frmPictureSizeModeClip the control


size can be changed without the picture size being modified. So you can see
only part of the picture or there can be a background behind it in a clolor color
you can change at will.

If the property is set to the 1-frmPictureSizeModeStretch the picture is resized


as the control is. The image fills the control.

If the property is set to the 3-frmPictureSizeModeZoom the picture is resized as


the control is but the picture and background are present.

47

También podría gustarte