You are on page 1of 47

Qu es una macro?

La definicin ms comn de una macro


es que se trata de un pequeo 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 referiran a instrucciones que iban ms all de los mens.

Para qu sirven las macros?


Para cualquier trabajo realizado en Excel, prcticamente. 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

Cmo grabar una macro Excel VBA


Para aprender a programar VBA de Excel la mejor manera de empezar es
probablemente la grabacin de macros en Excel. Es fcil grabar tus propias macros. Y
con un ligero retoque, salen todava mejor.

Preparar la grabacin
Entra Herramientas Macro Grabar nueva macro.

Nombre de la macro

Mtodo abreviado (atajo)

Guardar macro en

Descripcin

Pon un nombre descriptivo, por ejemplo


DosDecimales. Si quieres espacio entre palabras,
pon Dos_Decimales.
Si quieres que la macro se active desde el teclado,
pon la combinacin, por ejemplo CTRL + L.
Presionando MAYUSCULA te darn todava ms
combinaciones.
O se guarda en Este Libro, o en Libro de Macros
Personales. Si eliges Libro de Macros Personales,
la macro va a estar disponible desde cualquier
libro de Excel.
Si quieres puedes poner un texto explicativo el
cual se incluir en el cdigo de la macro.

Presiona OK. Ahora la macro grabar todo lo que pase a tu libro de Excel. Si
seleccionas celda H1, esa misma accin se grabar. Despus, al ejecutar la macro, esa
celda se seleccionar (sorpresa!). Entonces, mientras grabas, selecciona celda H1,
cambia el formato a Nmero 2 decimales. Paramos la grabacin.

Editar la macro grabada


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

Entra Mdulos Mdulo 1. A la derecha se ve lo que VBA te ha grabado. El cdigo


hace que Excel selecione celda H1, y que luego aplique un formato de nmero de dos
decimales. Es decir, la macro solo actuar sobre la celda H1.
Al cambiar el cdigo un poco podremos hacer que VBA cambie el formato a cualquier
celda que tengas seleccionada. Limpia el cdigo 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). Tambin puedes ejecutar la macro desde Herramientas Macro
Macros.

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 estarn accesibles. Esto es
una solucin eficaz para tus propios atajos, cmo por ejemplo Separador de miles, Pegar
valor etc.

Sobre el libro Personal.xls


Es un libro Excel normal y corriente, pero con unas determinadas caractersticas:

Tiene el nombre de Personal.xls


Contiene cdigo VBA para tus macros, funciones etc.
Se carga automticamente 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

Cmo se crea el libro Personal.xls?


Hay dos maneras de crear este libro.
1. Por tu cuenta
Crea un libro nuevo. Gurdalo 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 travs 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.

Alternativas a macros personales


En vez de colocar tus macros en el Libro de Macros Personales, podras 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 disposicin 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 ms comunes En poco tiempo tendrs
unas macros imprescindibles, y ya no podrs 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).

Alineacin 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

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 vacas


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 (Lneas de divisin)


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

Cambiar A1 a RC (columnas tiene nmeros 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

Introduccin a VBA de Excel


VBA (Visual Basic for Applications) es un lenguaje de macros utilizado para programar
pequeas aplicaciones dentro de un documento Excel, permitiendo la ampliacin de la
funcionalidad del mismo.

Aprende a programar macros Excel!


VBA es una modalidad adaptada del conocido lenguaje de programacin Visual Basic,
incluida en la mayora 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 introduccin a Excel VBA te ensear como empezar a desarrollar tus propias
macros Excel. VBA Excel y sus macros constituyen una ayuda potente para particulares
y pequeas y medianas empresas.
Excel, y sobre todo la aplicacin de macros VBA, mejora prcticamente cualquier
proceso de trabajo, desde sencillos clculos sobre la economa familiar hasta complejos
modelos empresariales de Excel para crear informes, presupuestos y dems documentos
financieros.

Todo el mundo puede aprender a programar macros?


Si, sin duda. Mucha gente empieza por la grabacin de macros, es decir grabar una
secuencia de comandos, para luego reutilizarla. Un buen ejemplo es Pegar Valores,
uno de los comandos VBA ms utilizados. Luego se pasa a una programacin VBA ms
compleja para buscar soluciones ms ntegras.

Qu es VBA?
VBA significa Visual Basic for
Applications. Es un lenguaje de
programacin que surge de Visual
Basic (VB). Se podra 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 aplicacin Excel).

Qu puedo hacer con


VBA?
Con este lenguaje de programacin
puedes crear tus propios programas en
Excel. Estos programas pueden ser
todo desde una macro (una pequea
programa VBA, por ejemplo un atajo
personalizado) hasta una aplicacin entera con listas desplegables, mens 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. Imagnate todas las tareas repetitivas que tienes que
ejecutar todos los das. Un ejemplo siempre vas aplicando el mismo formato a un
grupo de celdas de un libro que te mandan todos los das. En vez de hacer un montn de
clicks para obtener este formato, puedes automatizar el proceso, a un botn, o un atajo
de teclado.
Tambin puedes crear aplicaciones que importan datos desde el libro mayor,
reorganizan los datos, y crean informes personalizados para cada departamento. Casi no
hay lmites.

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 (Beginners All-purpose Symbolic Instruction
Code, o Cdigo de Instrucciones Simblicas de Uso General para Principiantes), el cual
en su turno es un lenguaje que tiene muchos aos ya (desde los aos 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 tambin tienen diferencias, por servir distintos

El editor VBA de Excel


El editor VBA sirve para controlar y manipular tu cdigo 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)/mtodos/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
Mdulos
Contenedores para el cdigo del proyecto
Formularios
Tus propios formularios, con controles (botones, mens + cdigo

A la derecha vemos el marcado del Objetos/Mdulos/Formularios.

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 evala todos estos nombres segn el
criterio Lo, uno por uno.
Hay dos tipos generales de bucles:

Bucles Do Loop
Repite las instrucciones mientras/hasta etc. una condicin es TRUE/VERDADERO.

Do While Loop / While Wend


Instruccin que repite las instrucciones mientras una condicin es
TRUE/VERDADERO.

Ejemplo
Excel tiene valores en las celdas B1:B100. Quieres buscar la primera celda que tenga un
valor ms 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

i = la lnea donde empezamos el bucle. Ponemos i = 1. Cells(i, 2) significar lnea i


(=1), columna 2. Es decir celda B1. Al final del bucle, i nos dar la lnea que buscamos.
Do While Cells(i, 2) <> significa que queremos que un bucle siga hasta que no hayan
ms celdas con valores en esta columna.
Aplicamos la condicin a cada celda, para luego salir del bucle (Exit Do) si encuentra
un valor igual a ms alto que 1,50 (VBA utiliza punto en vez de coma para
decimales).
Al final devolvemos un Messagebox para presentar el resultado.

Do Untilloop
Instruccin que repite las instrucciones hasta que una condicin 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
1
2
3
4
5
6

Alberto
Alejandro
Alex
Alexis
Allain

i = 1
Do Until Cells(i, 1) = "Alexis"
i = i + 1
Loop
MsgBox "El nombre Alexis se encontr en la lnea " & i

i = la lnea donde empezamos el bucle. Ponemos i = 1. Cells(i, 1) significar lnea i


(=1), columna 1.
Es decir celda A1. Al final del bucle, i nos dar la lnea 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 dilogo para presentar el resultado, cual en este caso
sera 4.

10

Bucles For Next


Repite las instrucciones un nmero especificado de veces.

For i Next
Esta instruccin se repite el nmero 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 atrs, pondramos step -1.
intValor = 1
For i = 1 to 4 step 1
intValor = intValor
Next i

+ 2

For Each Next


Instruccin que repite las instrucciones segn el nmero 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 condicin.
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 ms frecuentes tipos de variable de Excel VBA.
Tipo
Bytes Descripcin
Byte
1
0-255
Boolean
1
True/False
Integer
2
-32.768 hasta +
Long (long int.) 4
-2.147.483.648 hasta +
Single
4
-3,402823 E38 hasta +
Double
8
-1,79769313486232 E308 hasta +
Currency
8
15 dg. + 4 decimales
Date
8
1-ene-100 hasta 31-dic-9999
Object
4
referencia a objetos
String
10+ carcteres Ascii (texto)
String (long. fija) 1+ carcteres Ascii, longitud predef.
Variant
16+ cualquier tipo de datos

Comentario
Integrales positivos
Valores discretos
Integrales
Integrales
Decimales
Decimales
Nmero, 4 dec.
Fechas
Ej. Workbook
Texto
Texto
Cubre la mayora

Declarar variables
Porqu declarar variables?
El cdigo saldr ms estructurado
Si no declaras un variable, no sabrs que tipo de datos contendr.
Es ms seguro evitars errores tipogrficos
VBA te ayudar a poner los nombres correctos. Si no, un error tipogrfico puede parar
el programa.
El cdigo trabajar ms eficaz
Variables no declaradas sern tratados como Variants, las cuales ocupan mucha ms
memoria.
Te ayudar a programar
VBA te ayuda a elegir propiedades/mtodos 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 nmero de dimensiones que la
variable va a tener (ej. guardar nmeros dentro de una variable, en 3 dimensiones).
Para que sea ms fcil leer el cdigo, 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 cdigo. No obstante, la posicin puede
dar resultados distintos. Por eso es recomendable seguir unas normas.
Tipo de declaracin Ubicacin
Encima del procedimiento (antes
Dim
del primer Sub)
Antes de un procedimiento
Dim
especfico.
Dim
Dentro de un procedimiento.
Encima del procedimiento (antes
Public
del primer Sub)

Accesible
Todos los procedimientos del
mdulo.
Ese procedimiento.
Resto de ese procedimiento.
Todos los procedimientos (de
todos los mdulos).

13

VBA de Excel ejemplos prcticos 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 funcin de Pegar como valor en Excel.
Estas pequeas aplicaciones suelen denominarse macros, pero Excel VBA tambin
sirve para la programacin de aplicaciones ms complejas, como servicios de bases de
datos y la manipulacin de archivos.

Ejemplos de macros VBA de Excel


Esta lista de ejemplos VBA de Excel recopila algunas pequeas aplicaciones de cdigo
VBA. Recuerda haz una copia de seguridad antes de aplicar cdigo VBA a tus
archivos.

Excel y otros programas

Visual Basic importar datos de Excel


Microsoft Excel es una aplicacin muy flexible y permite la comunicacin 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
aplicacin. A continuacin detallamos cmo proceder para establecer contacto entre
Excel y Visual Basic.

Exportar Excel a Visual Basic


Excel permite la exportacin de datos a un montn de aplicaciones como de Visual
Basic, bases de datos, XML etc. Es este ejemplo Excel presentamos una solucin 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 clculo

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

Cdigo 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 funcin VBA de Create Object. Esta funcin 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 importacin se va a
realizar, mediante el dilogo 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
Dim
Dim
Dim
Dim

strWordArchivo As Variant
i, r, intLineas As Integer
appWord As Word.Application
appDoc As Word.Document
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 aplicacin 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 (dilogo)


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 posicin)


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

Insertar hoja nueva (primera posicin)


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

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

Ordenar hojas (orden alfabtico)


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 disposicin un montn de formatos. Abajo presentamos como modificar
algunos de ellos a travs 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

Lneas de divisin
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 revs)


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 vacas


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 vacas


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 vacas


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 condicin


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 vacas por dos condicines 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 revs)


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 vacas 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 cdigo VBA. Abajo presentamos unos
ejemplos de cdigo 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 difcil de leer.
Los colores forman parte del diseo del libro, son importantes para una buena
presentacin 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. Tambin
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 solucin sera crear una plantilla con nuestros formatos. Excel llamar esta
plantilla al crear un libro nuevo.
Otra solucin es crear una macro cual nosotros podemos llamar cuando nos convenga.
Esto nos da un poco ms 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)

Cdigo 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 mtodo ResetColors.
ActiveWorkbook.ResetColors

Copiar colores de otro libro Excel


Tambin 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 cdigo 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 cdigo en los
objetos de las hojas. En ejemplo abajo habra
que poner el cdigo en los contenedores de
cdigo de una o ms 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 funcin no est integrada en Excel
(sorprendentemente), por eso hay que recurrir a VBA.

Eventos empleados para la proteccin


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 errnea, se queda en la hoja
anterior.

Grado de seguridad de la macro para proteger hojas


Cualquier persona puede entrar al cdigo VBA para ver la palabra de paso. Por eso
debes proteger el cdigo (VBA editor Click derecho sobre EsteLibro Propiedades).
Este mtodo no da 100% de seguridad. Si activamos la proteccin de los mdulos 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 cdigo en el contenedor EsteLibro del editor VBA (Herramientas Macro
Editor VBA).
Luego tienes que poner que hojas/palabra de paso (ver Preparar modelo del cdigo).

Cdigo 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/nmeros]
'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) convendra 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 mximo 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 mdulo dentro de este libro. En este mdulo escribimos el cdigo.
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 cdigo sirve para abrir otro libro Excel a travs del dilogo Abrir. All el usuario
elige el libro a abrir. Si el usuario pulsa Cancelar, el dilogo 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 bsico en muchos de tus futuros
programas de Excel VBA.
Sub Abrir_archivo()
Dim strRutaArchivo As String
'un poco de informacin
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 fciles de usar), y crea una interfaz entre el usuario y
el programa. Sirven para

Mostrar informacin al usuario


Recibir informacin del usuario
Devolver informacin del usuario

Construccin sintctica de la messagebox


Msgbox "Mensaje", Botones/conos, "Ttulo"

o en el caso de devolver informacin


Respuesta = Msgbox("Mensaje", Botones/conos, "Ttulo")

Nota las parntesis en la segunda construccin.

Mensaje
Cualquier tipo de texto. Para crear un salto de lnea empleamos el carcter vbCrLf.
Actualizacin terminada:" & vbCrLf & "- Importacin de datos de venta.

Botones
Si quieres puedes aadir 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

Ttulo
Cualquier texto.

Devolver informacin
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 mdelo para que te vayas acostumbrando a las diferentes
messagebox.
Sub MessageBox()
msgbox "Actualizacin terminada:", _
vbOKOnly, "Informacin"
End Sub

Sub MessageBox()
msgbox "Quieres seguir?", vbYesNo, "Informacin importante"
End Sub

30

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

Sub MessageBox()
msgbox "Actualizacin terminada:" & _
vbCrLf & vbCrLf & _
"- Importacin de datos de venta." & vbCrLf & _
"- Clculos de impuestos." & vbCrLf & _
"- Venta por proveedor." & vbCrLf _
, vbOKOnly, "Actualizacin terminada."
End Sub

Sub MessageBox()
msgbox "Actualizacin terminada:" & vbCrLf & vbCrLf & _
"- Importacin de datos de venta." & vbCrLf & _
"- Clculos de impuestos." & vbCrLf & _
"- Venta por proveedor." & vbCrLf _

31

, vbExclamation + vbOKOnly, _
"Actualizacin terminada."
End Sub

Sumar rangos variables con VBA Excel


Sumar un rango en Excel es fcil. Sumar un rango expresado por una variable en VBA
es un poco ms complicado (pero sigue siendo fcil).
No siempre se sabe de antemano que celdas formarn parte del rango a sumar. Entonces
tenemos que expresar el rango de forma variable.
En Excel es fcil sumar este rango mediante una sencilla frmula. Pero VBA no
contiene ninguna funcin 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 funcin SUM de Excel.
Application.WorksheetFunction.Sum(varSuma)

De esta manera puedes aplicar cualquier frmula de Excel en VBA, con tal de que
empieces la lnea de cdigo 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

DOCUMENTACIN EN INGLS
Obtenido desde la direccin : 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
and, the frame this one

, the check box has 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

You might also like