Professional Documents
Culture Documents
Preparar la grabacin
Entra Herramientas Macro Grabar nueva macro.
Nombre de la macro
Guardar macro en
Descripcin
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.
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.
Alineacin 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
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
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).
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).
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
Bucles Do Loop
Repite las instrucciones mientras/hasta etc. 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
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
10
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
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.
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.
Accesible
Todos los procedimientos del
mdulo.
Ese procedimiento.
Resto de ese procedimiento.
Todos los procedimientos (de
todos los mdulos).
13
14
15
strWordArchivo As Variant
i, r, intLineas As Integer
appWord As Word.Application
appDoc As Word.Document
rngDoc As Word.Range
16
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
17
Mover hoja
Worksheets("informe5").Move After:=Worksheets("Informe4")
18
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
Letra Negrita
Selection.Font.Bold = True
Letra Cursiva
Selection.Font.Italic = True
Letra Subrayada
Selection.Font.Underline = True
20
Next r
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
22
23
24
Item.Interior.ColorIndex = 44
End If
Next
25
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).
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
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
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
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
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
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
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
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
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
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