Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Macrosvba PDF
Macrosvba PDF
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.
Preparar la grabación
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.
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?
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..
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.
Alineación izquierda/derecha
Sub Ajustar_izq_der()
If Selection.HorizontalAlignment = xlRight Then
Selection.HorizontalAlignment = xlLeft
Else
Selection.HorizontalAlignment = xlRight
End If
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
Autofilter
Sub FilterExcel()
Selection.AutoFilter
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
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.
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?
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
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
Contenido de un proyecto
En la columna de izquierda tenemos las piezas que forman parte del proyecto. En este
ejemplo tenemos dos libros abiertos:
8
VBA bucles Intro
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.
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
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).
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
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
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
11
VBA Variables
Tipos de variables
Abajo presentamos los más frecuentes tipos de variable de Excel VBA.
Declarar variables
¿Porqué declarar variables?
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.
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.
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.
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.
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.
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.
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
'dimensiones
Dim xlApp As Excel.Application
Dim xlLibro As Excel.Workbook
Dim xlHoja As Excel.Worksheet
Dim varMatriz As Variant
Dim lngUltimaFila As Long
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()
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
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()
With appWord
.Visible = True
.Activate
End With
End Sub
17
Cerrar libro Excel (variable, sin guardar cambios)
Application.DisplayAlerts = False
Windows(Libro_mayor).Close
Application.DisplayAlerts = True
strArchivo = Application.GetOpenFilename
On Error GoTo 99
Mover hoja
Worksheets("informe5").Move After:=Worksheets("Informe4")
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
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
20
Next r
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
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
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
DeleteRange =("A1:B10")
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
DeleteRange =("A1:B10")
With DeleteRange
cCount = .Columns.Count
For c = n To cCount Step n - 1
Columns(c).EntireColumn.Delete
Next c
End With
End Sub
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 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.
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
Para resetear los colores a los predefinidos de Excel, aplicamos el método ResetColors.
ActiveWorkbook.ResetColors
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
A lo mejor nos interesa saber que color tiene una celda. La propiedad ColorIndex nos
ayuda.
i = Cells(1, 1).Interior.ColorIndex
MsgBox i
Podemos colorear celdas por condiciones, evaluando una cadena de texto, por ejemplo.
24
Item.Interior.ColorIndex = 44
End If
Next
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.
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.
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).
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).
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
99:
'conectar Events
Application.EnableEvents = True
End Sub
'*************************************************
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()
27
'en que fila/columna empezar la lista
intFila = 4
intColumna = 1
'crear links
If wsHoja.Name <> wrsHojaActiva.Name Then
intFila = intFila + 1
End If
ProxHoja:
Next wsHoja
End Sub
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()
'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
Mensaje
Cualquier tipo de texto. Para crear un salto de línea empleamos el carácter vbCrLf.
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
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
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.
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)
33
DOCUMENTACIÓN EN INGLÉS
Obtenido desde la dirección : http://www.excel-vba.com/excel-vba-contents.htm
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
Range("A1").Select
End Sub
Step 3: Run the macro from Excel as you did with the previous one.
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
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.
ThisWorkbook
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
When you work with two workbooks you will move from one to the other with:
ThisWorkbook.Activate
Windows("theOtherWorkbookName.xls").Activate
Sheets
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.
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
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 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.
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
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()
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
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.
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.
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.
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
- WordWrap: If you want to write more than one line of text in a label set this
property to "True" .
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.
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).
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.
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
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.
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.
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 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.
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
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.
Spin Button
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
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.
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
47