Excel VBA Programming (Statements & Functions)
Excel VBA Programming (Statements & Functions)
http://www.dummies.com/how-to/content/excel-vba-programming-for-dummies-cheat-sheet.html
VBA On...GoSub Branches, based on a condition
What It Does
Statement On...GoTo Branches, based on a condition
AppActivate Activates an application window Open Opens a text file
Beep Sounds a tone via the computer's speaker Option Base Changes the default lower limit for arrays
Call Transfers control to another procedure Option Declares the default comparison mode when
ChDir Changes the current directory Compare comparing strings
ChDrive Changes the current drive Option Explicit Forces declaration of all variables in a module
Close Closes a text file Option Private Indicates that an entire module is Private
Const Declares a constant value Print # Writes data to a sequential file
Date Sets the current system date Private Declares a local array or variable
Declares a reference to an external procedure Declares the name and arguments of a
Declare Property Get
in a Dynamic Link Library (DLL) Property Get procedure
Deletes a section or key setting from an Declares the name and arguments of a
DeleteSetting Property Let
application's entry in the Windows Registry Property Let procedure
Declares variables and (optionally) their data Declares the name and arguments of a
Dim Property Set
types Property Set procedure
Do-Loop Loops through a set of instructions Public Declares a public array or variable
Used by itself, exits the program; also used to Put Writes a variable to a text file
End end a block of statements that begin with If, RaiseEvent Fires a user-defined event
With, Sub, Function, Property, Type, or Select
Randomize Initializes the random number generator
Erase Re-initializes an array
ReDim Changes the dimensions of an array
Error Simulates a specific error condition
Specifies a line of comments (same as an
Exit Do Exits a block of Do-Loop code Rem
apostrophe ['])
Exit For Exits a block of For-Next code Reset Closes all open text files
Exit Function Exits a Function procedure Resumes execution when an error-handling
Resume
Exit Property Exits a property procedure routine finishes
Exit Sub Exits a subroutine procedure RmDir Removes an empty directory
FileCopy Copies a file Saves or creates an application entry in the
SaveSetting
Loops through a set of instructions for each Windows Registry
For Each-Next Sets the position for the next access in a text
member of a collection
Seek
Loops through a set of instructions a specific file
For-Next Select Case Processes statements conditionally
number of times
Declares the name and arguments for a SendKeys Sends keystrokes to the active window
Function
Function procedure Assigns an object reference to a variable or
Set
Get Reads data from a text file property
GoSub...Return Branches to and returns from a procedure SetAttr Changes attribute information for a file
Branches to a specified statement within a Declares variables at the procedure level so
GoTo that the variables retain their values as long as
procedure
Static
Processes statements conditionally (the Else the code is running and the project hasn't been
If-Then-Else reset.
part is optional)
Input # Reads data from a sequential text file Stop Pauses the program
Kill Deletes a file Declares the name and arguments of a Sub
Sub
procedure
Assigns the value of an expression to a variable
Let Time Sets the system time
or property
Line Input # Reads a line of data from a sequential text file Type Defines a custom data type
Load Loads an object but doesn't show it Unload Removes an object from memory
Lock...Unlock Controls access to a text file Loops through a set of instructions as long as a
While...Wend
certain condition remains true
Replaces characters in a string with other
Mid Width # Sets the output line width of a text file
characters
MkDir Creates a new directory Allows a shorthand way of accessing multiple
With
properties for an object
Name Renames a file or directory
Write # Writes data to a sequential text file
Gives specific instructions for what to do in the
On Error
case of an error
The following table shows the Visual Basic data types, their supporting common language runtime types,
their nominal storage allocation, and their value ranges.
Common
Visual Basic
language runtime Nominal storage allocation Value range
type
type structure
Depends on implementing
Boolean Boolean True or False
platform
Byte Byte 1 byte 0 through 255 (unsigned)
Char (single
Char 2 bytes 0 through 65535 (unsigned)
character)
Date DateTime 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999
0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28) † with no
decimal point; 0 through +/-7.9228162514264337593543950335 with 28 places to
Decimal Decimal 16 bytes the right of the decimal;
smallest nonzero number is +/-0.0000000000000000000000000001 (+/-1E-28) †
Double -1.79769313486231570E+308 through -4.94065645841246544E-324 † for negative
(double- values;
Double 8 bytes 4.94065645841246544E-324 through 1.79769313486231570E+308 † for positive
precision
floating-point) values
Integer Int32 4 bytes -2,147,483,648 through 2,147,483,647 (signed)
Long (long -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 (9.2...E+18 †)
Int64 8 bytes (signed)
integer)
4 bytes on 32-bit platform
Object Object (class) Any type can be stored in a variable of type Object
8 bytes on 64-bit platform
SByte SByte 1 byte -128 through 127 (signed)
Short (short
Int16 2 bytes -32,768 through 32,767 (signed)
integer)
Single (single-
-3.4028235E+38 through -1.401298E-45 † for negative values;
precision Single 4 bytes 1.401298E-45 through 3.4028235E+38 † for positive values
floating-point)
String
Depends on implementing
(variable- String (class) 0 to approximately 2 billion Unicode characters
platform
length)
UInteger UInt32 4 bytes 0 through 4,294,967,295 (unsigned)
ULong UInt64 8 bytes 0 through 18,446,744,073,709,551,615 (1.8...E+19 †) (unsigned)
User-Defined (inherits from Depends on implementing Each member of the structure has a range determined by its data type and
(structure) ValueType) platform independent of the ranges of the other members
UShort UInt16 2 bytes 0 through 65,535 (unsigned)
† In scientific notation, "E" refers to a power of 10. So 3.56E+2 signifies 3.56 x 102 or 356, and 3.56E-2 signifies 3.56 / 102 or 0.0356.
Atajos VB
Alt+F11 Open the VBA editor F1 Get help on any selected item
Ctrl+Break Perform an emergency stop of the program F4 Display the Properties window
Ctrl+I List the quick information for the selected element F7 Display the Code window after selecting a form or control
Ctrl+J List the properties and methods for an object F9 Add a breakpoint
Ctrl+Shift+J List the constants associated with an enumeration Ctrl+Tab Move to the next Code or UserForm window
Descripción de las funciones de VBA y sus usos
Una función realiza un cálculo y devuelve un solo valor. La función SUM añade la suma de un rango de valores. Lo mismo es válido para las
funciones utilizadas en sus expresiones de VBA: Cada función hace su cosa y devuelve un solo valor.
VBA ofrece numerosas funciones incorporadas. Algunas de estas funciones toman argumentos y otros no.
Aquí están algunos ejemplos del uso de las funciones de VBA en el código. Observe el uso de la función MsgBox para mostrar un valor en un
cuadro de mensaje. Sí, es una función MsgBox de VBA - una bastante inusual, pero una función, no obstante. Esta útil función muestra un
mensaje en un cuadro de diálogo emergente.
El primer ejemplo utiliza la función Fecha de VBA para mostrar la fecha actual del sistema en un cuadro de mensaje:
VerFecha Sub ()
MsgBox Fecha
End Sub
Observe que la función Fecha no utiliza un argumento. A diferencia de las funciones de hoja, una función VBA sin argumentos no requiere de
un conjunto de paréntesis vacío. De hecho, si usted proporciona un conjunto vacío de paréntesis, el VBE los eliminará.
Para obtener la fecha y hora del sistema, utilice la función Ahora, en lugar de la función Fecha. O para obtener sólo el tiempo, use la función
Time.
El siguiente procedimiento utiliza la función VBA Len, que devuelve la longitud de una cadena. La función Len toma un argumento: la cadena.
Cuando se ejecuta este procedimiento, el cuadro de mensaje muestra 11 porque el argumento tiene 11 caracteres.
Sub GetLength ()
Dim MiCadena As String
Dim StringLength As Integer
MyString = "Hello World"
StringLength = Len (MiCadena)
MsgBox StringLength
End Sub
Excel también tiene una función, que puede utilizar en sus fórmulas de hoja de cálculo. La versión de Excel y la función VBA funcionan de la
misma.
El siguiente procedimiento utiliza la función de corrección, que devuelve la parte entera de un valor - el valor sin dígitos decimales:
Sub GetIntegerPart ()
Dim MyValue As Double
Dim intValue As Integer
MyValue = 123.456
IntValue = Fix (MyValue)
MsgBox intValue
End Sub
VBA tiene una función similar llamada Int. La diferencia entre Int y Fix es cómo cada ofertas con números negativos.
Int devuelve el primer entero negativo que es menor o igual que el argumento.
Fix devuelve el primer entero negativo que es mayor que o igual al argumento.
El siguiente procedimiento Sub muestra el tamaño en bytes del archivo ejecutable de Excel. Se encuentra este valor utilizando la función
FileLen.
Sub GetFileSize ()
Dim thefile As String
Thefile = "c: \ MSOffice \ EXCEL \ EXCEL.EXE"
MsgBox FileLen (thefile)
End Sub
Tenga en cuenta que esta rutina impide la modificación del nombre de archivo (es decir, se establece explícitamente la ruta). Generalmente,
esto no es una buena idea. El archivo podría no estar en la unidad C, o en la carpeta Excel puede tener un nombre diferente. La siguiente
declaración muestra un mejor enfoque:
Path es una propiedad del objeto Application. Simplemente devuelve el nombre de la carpeta en la que está instalada la aplicación (es decir,
Excel) (sin una barra diagonal inversa).
El siguiente procedimiento utiliza la función TypeName, que devuelve el tipo de objeto seleccionado (como una cadena):
ShowSelectionType Sub ()
SelType Dim As String
SelType = TypeName (Selección)
MsgBox SelType
End Sub
Esto podría ser un rango, un ChartObject, un cuadro de texto, o cualquier otro tipo de objeto que se puede seleccionar.
La función TypeName es muy versátil. También puede utilizar esta función para determinar el tipo de datos de una variable.
Unas pocas funciones VBA ir por encima y más allá del llamado del deber. En lugar de simplemente devolver un valor, estas funciones tienen
algunos efectos secundarios útiles. Tabla 1 los enumera.
MsgBox Muestra un cuadro de diálogo práctico que contiene un mensaje y botones. La función devuelve un código que identifica el botón
que el usuario hace clic.
InputBox Muestra un cuadro de diálogo simple que ordena al usuario alguna información. La función devuelve lo que el usuario entra en el
cuadro de diálogo.
Cáscara Ejecuta otro programa. La función devuelve el ID de tarea (un identificador único) del otro programa (o un error si la función no se
puede iniciar el otro programa).
¿Cómo saber qué funciones VBA ofrece? Buena pregunta. La mejor fuente es el sistema de Ayuda de Visual Basic de Excel. Tabla 2 contiene
una lista parcial de las funciones (menos algunas de las funciones más especializadas o oscuros).
Para más detalles sobre una función en particular, escriba el nombre de la función en un módulo VBA, mueva el cursor en cualquier parte del
texto y pulse F1.
Tabla 2: más útiles funciones incorporadas en VBA
Abs Devuelve el valor absoluto de un número GetSetting Devuelve un valor en el registro de Windows
Colección Devuelve una variante que contiene una matriz Maleficio Convierte de decimal a hexadecimal
Asc Convierte el primer carácter de una cadena a su Hora Devuelve la parte de horas de un tiempo
valor ASCII
InputBox Muestra un cuadro de solicitar a un usuario para
Atn Devuelve la arcotangente de un número la entrada
Elegir Devuelve un valor de una lista de artículos InStr Devuelve la posición de una cadena dentro de
otra cadena
Chr Convierte un valor ANSI a una cadena
Int Devuelve la parte entera de un número
Cos Devuelve el coseno de un número
PAGOINT Devuelve el pago de intereses de una anualidad o
CurDir Devuelve la ruta actual préstamo
Fecha Devuelve la fecha actual del sistema IsArray Devuelve True si una variable es una matriz
DateAdd Devuelve una fecha a la que un intervalo de IsDate Devuelve True si una expresión es una fecha
tiempo especificado ha sido
IsEmpty Devuelve True si una variable no se ha
añadido - por ejemplo, un mes a partir de una inicializado
fecha determinada
EsError Devuelve True si una expresión es un valor de
DateDiff Devuelve un entero que indica el número de error
intervalos de tiempo especificados entre dos
fechas, por ejemplo el número de meses entre el IsMissing Devuelve True si un argumento opcional no se
momento actual y su cumpleaños pasa a un procedimiento
DatePart Devuelve un entero que contiene la parte IsNull Devuelve True si una expresión no contiene
específica de un determinado datos válidos
fecha - por ejemplo, un día de la fecha del año IsNumeric Devuelve True si una expresión se puede evaluar
como un número
Dir Devuelve el nombre de un archivo o directorio LCase Devuelve una cadena convertida a minúsculas
que coincide con un patrón
Izquierda Devuelve un número especificado de caracteres
Erl Devuelve el número de línea que provocó un de la izquierda de una cadena
error
Len Devuelve el número de caracteres de una cadena
Errar Devuelve el número de error de una condición de
error
Iniciar Devuelve el logaritmo natural de un número en
sesión base e
Error Devuelve el mensaje de error que corresponde a
un número de error
LTrim Devuelve una copia de una cadena, con los
principales espacios retirados
Exp Devuelve la base del logaritmo natural (e)
elevado a una potencia
Medio Devuelve un número especificado de caracteres
de una cadena
FileLen Devuelve el número de bytes en un archivo
RTrim Devuelve una copia de una cadena, con los Recortar Devuelve una cadena sin espacios iniciales o
espacios finales retirados finales
Segundo Devuelve la parte de segundo de un valor de TypeName Devuelve una cadena que describe el tipo de
tiempo datos de una variable
Sgn Devuelve un entero que indica el signo de un UBound Devuelve el mayor subíndice disponible para la
número dimensión de una matriz
Seno Devuelve seno de un número Val Devuelve los números contenidos en una cadena
Espacio Devuelve una cadena con un número VarType Devuelve un valor que indica el subtipo de una
determinado de espacios variable
Sqr Devuelve la raíz cuadrada de un número Día Devuelve un número que representa un día de la
laborable semana
Str Devuelve una representación de cadena de un
número Año Devuelve el año a partir de un valor de fecha