VBA – Cómo Utilizar las Funciones de Hoja de Cálculo (y una Lista Completa)

Written by

Editorial Team

Reviewed by

Steve Rynearson

Translated by

Dennis Madrid

Last updated on abril 28, 2023

Hay muchas maneras de utilizar funciones en VBA. VBA viene cargado con muchas funciones incorporadas. Incluso puede crear sus propias funciones (UDFs). Sin embargo, también puede utilizar muchas de las funciones de Excel en VBA utilizando Application.WorksheetFunction.

Cómo Utilizar Funciones de Hoja de Cálculo en VBA

Para acceder a una función de Excel en VBA añada Application.WorksheetFunction delante de la función que desea llamar. En el siguiente ejemplo, llamaremos a la Función Max de Excel:

Dim maxvalue as long
maxvalue = Application.WorksheetFunction.Max(Range("A1").Value, Range("A2").Value)

La sintaxis de las funciones es la misma, sin embargo usted ingresará los argumentos de la función tal como lo haría con cualquier otra función VBA.

Note que la sintaxis de la Función Max aparece cuando usted escribe (similar a las Funciones VBA):

Sintaxis Función WorksheetFunction Max

 

Método WorksheetFunction

WorksheetFunction es un método del objeto Application. Le permite acceder a muchas (no todas) de las funciones estándar de la hoja de cálculo de Excel. Generalmente, no tendrás acceso a ninguna función de hoja de cálculo que tenga su correspondiente versión VBA.

A continuación puede ver una lista de muchas de las Funciones de Hoja de Cálculo más comunes.

Application.WorksheetFunction vs. Application

En realidad hay dos formas de acceder a estas funciones: Application.WorksheetFunction (como se ve arriba):

maxvalue = Application.WorksheetFunction.Max(Range("a1").Value, Range("a2").Value)

o puede omitir WorksheetFunction

maxvalue = Application.Max(Range("a1").Value, Range("a2").Value)

Desafortunadamente, omitir la WorksheetFunction eliminará el Intellisense que muestra la sintaxis (ver imagen anterior). Sin embargo, tiene una gran ventaja potencial: Manejo de Errores.

Si utiliza Application, y su función genera un error devolverá el valor del error. Si utiliza el método WorksheetFunction, VBA arrojará un error en tiempo de ejecución. Por supuesto, usted puede manejar el error de VBA, pero generalmente es mejor evitar el error en primer lugar. Veamos un ejemplo para ver la diferencia:

Manejo de Errores de la Función de Hoja de Cálculo Vlookup

Intentaremos realizar un Vlookup que no resultará en una coincidencia. Por lo tanto, la función Vlookup devolverá un error.

Primero, utilizaremos el método WorksheetFunction. Observe como VBA arroja un error:

A continuación omitimos WorksheetFunction. Observe cómo

Ejemplo Método WorksheetFunction

A continuación omitiremos la función WorksheetFunction. Observe como no se lanza ningún error y en su lugar la función ‘valor’ contiene el valor de error del Vlookup.

Ejemplo Application

 

Lista de Funciones de Hoja de Cálculo VBA

A continuación encontrará una lista de la mayoría de los comunes VBA WorksheetFunctions.

FunctionDescription
Logical
ANDChecks whether all conditions are met. TRUE/FALSE
IFIf condition is met, do something, if not, do something else.
IFERRORIf result is an error then do something else.
ORChecks whether any conditions are met. TRUE/FALSE
Lookup & Reference
CHOOSEChooses a value from a list based on it's position number.
HLOOKUPLookup a value in the first row and return a value.
INDEXReturns a value based on it's column and row numbers.
LOOKUPLooks up values either horizontally or vertically.
MATCHSearches for a value in a list and returns its position.
TRANSPOSEFlips the oriention of a range of cells.
VLOOKUPLookup a value in the first column and return a value.
Date & Time
DATEReturns a date from year, month, and day.
DATEVALUEConverts a date stored as text into a valid date
DAYReturns the day as a number (1-31).
DAYS360Returns days between 2 dates in a 360 day year.
EDATEReturns a date, n months away from a start date.
EOMONTHReturns the last day of the month, n months away date.
HOURReturns the hour as a number (0-23).
MINUTEReturns the minute as a number (0-59).
MONTHReturns the month as a number (1-12).
NETWORKDAYSNumber of working days between 2 dates.
NETWORKDAYS.INTLWorking days between 2 dates, custom weekends.
NOWReturns the current date and time.
SECONDReturns the second as a number (0-59)
TIMEReturns the time from a hour, minute, and second.
TIMEVALUEConverts a time stored as text into a valid time.
WEEKDAYReturns the day of the week as a number (1-7).
WEEKNUMReturns the week number in a year (1-52).
WORKDAYThe date n working days from a date.
YEARReturns the year.
YEARFRACReturns the fraction of a year between 2 dates.
Engineering
CONVERTConvert number from one unit to another.
Financial
FVCalculates the future value.
PVCalculates the present value.
NPERCalculates the total number of payment periods.
PMTCalculates the payment amount.
RATECalculates the interest Rate.
NPVCalculates the net present value.
IRRThe internal rate of return for a set of periodic CFs.
XIRRThe internal rate of return for a set of non-periodic CFs.
PRICECalculates the price of a bond.
INTRATEThe interest rate of a fully invested security.
Information
ISERRTest if cell value is an error, ignores #N/A. TRUE/FALSE
ISERRORTest if cell value is an error. TRUE/FALSE
ISEVENTest if cell value is even. TRUE/FALSE
ISLOGICALTest if cell is logical (TRUE or FALSE). TRUE/FALSE
ISNATest if cell value is #N/A. TRUE/FALSE
ISNONTEXTTest if cell is not text (blank cells are not text). TRUE/FALSE
ISNUMBERTest if cell is a number. TRUE/FALSE
ISODDTest if cell value is odd. TRUE/FALSE
ISTEXTTest if cell is text. TRUE/FALSE
TYPEReturns the type of value in a cell.
Math
ABSCalculates the absolute value of a number.
AGGREGATEDefine and perform calculations for a database or a list.
CEILINGRounds a number up, to the nearest specified multiple.
COSReturns the cosine of an angle.
DEGREESConverts radians to degrees.
DSUMSums database records that meet certain criteria.
EVENRounds to the nearest even integer.
EXPCalculates the exponential value for a given number.
FACTReturns the factorial.
FLOORRounds a number down, to the nearest specified multiple.
GCDReturns the greatest common divisor.
INTRounds a number down to the nearest integer.
LCMReturns the least common multiple.
LNReturns the natural logarithm of a number.
LOGReturns the logarithm of a number to a specified base.
LOG10Returns the base-10 logarithm of a number.
MROUNDRounds a number to a specified multiple.
ODDRounds to the nearest odd integer.
PIThe value of PI.
POWERCalculates a number raised to a power.
PRODUCTMultiplies an array of numbers.
QUOTIENTReturns the integer result of division.
RADIANSConverts an angle into radians.
RANDBETWEENCalculates a random number between two numbers.
ROUNDRounds a number to a specified number of digits.
ROUNDDOWNRounds a number down (towards zero).
ROUNDUPRounds a number up (away from zero).
SINReturns the sine of an angle.
SUBTOTALReturns a summary statistic for a series of data.
SUMAdds numbers together.
SUMIFSums numbers that meet a criteria.
SUMIFSSums numbers that meet multiple criteria.
SUMPRODUCTMultiplies arrays of numbers and sums the resultant array.
TANReturns the tangent of an angle.
Stats
AVERAGEAverages numbers.
AVERAGEIFAverages numbers that meet a criteria.
AVERAGEIFSAverages numbers that meet multiple criteria.
CORRELCalculates the correlation of two series.
COUNTCounts cells that contain a number.
COUNTACount cells that are non-blank.
COUNTBLANKCounts cells that are blank.
COUNTIFCounts cells that meet a criteria.
COUNTIFSCounts cells that meet multiple criteria.
FORECASTPredict future y-values from linear trend line.
FREQUENCYCounts values that fall within specified ranges.
GROWTHCalculates Y values based on exponential growth.
INTERCEPTCalculates the Y intercept for a best-fit line.
LARGEReturns the kth largest value.
LINESTReturns statistics about a trendline.
MAXReturns the largest number.
MEDIANReturns the median number.
MINReturns the smallest number.
MODEReturns the most common number.
PERCENTILEReturns the kth percentile.
PERCENTILE.INCReturns the kth percentile. Where k is inclusive.
PERCENTILE.EXCReturns the kth percentile. Where k is exclusive.
QUARTILEReturns the specified quartile value.
QUARTILE.INCReturns the specified quartile value. Inclusive.
QUARTILE.EXCReturns the specified quartile value. Exclusive.
RANKRank of a number within a series.
RANK.AVGRank of a number within a series. Averages.
RANK.EQRank of a number within a series. Top Rank.
SLOPECalculates the slope from linear regression.
SMALLReturns the kth smallest value.
STDEVCalculates the standard deviation.
STDEV.PCalculates the SD of an entire population.
STDEV.SCalculates the SD of a sample.
STDEVPCalculates the SD of an entire population
TRENDCalculates Y values based on a trendline.
Text
CLEANRemoves all non-printable characters.
DOLLARConverts a number to text in currency format.
FINDLocates position of text within a cell.Case-sensitive.
LEFTTruncates text a number of characters from the left.
LENCounts number of characters in text.
MIDExtracts text from the middle of a cell.
PROPERConverts text to proper case.
REPLACEReplaces text based on it's location.
REPTRepeats text a number of times.
RIGHTTruncates text a number of characters from the right.
SEARCHLocates position of text within a cell.Not Case-sensitive.
SUBSTITUTEFinds and replaces text. Case-sensitive.
TEXTConverts a value into text with a specific number format.
TRIMRemoves all extra spaces from text.
vba-free-addin

Complemento de Ejemplos de Código de VBA

Acceda fácilmente a todos los ejemplos de código que se encuentran en nuestro sitio.

Simplemente navegue al menú, haga clic y el código se insertará directamente en su módulo. Complemento .xlam.

(¡No se requiere instalación!)

Descarga gratuita

Return to VBA Code Examples