VBA Functions VBA Functions - By Category TECH ont he Net String Functions: ASC (VBA) CHR (VBA) Concatenate with & (WS, VBA) CURDIR (VBA) FORMAT Strings (VBA) INSTR (VBA) INSTRREV (VBA) LCASE (VBA) LEFT (WS, VBA) LEN (WS, VBA) LTRIM (VBA) MID (WS, VBA) REPLACE (VBA) RIGHT (WS, VBA) RTRIM (VBA) SPACE (VBA) STR (VBA) STRCONV (VBA) TRIM (WS, VBA) UCASE (VBA) VAL (VBA) Date & Time Functions: DATE (VBA) DATEADD (VBA) DATEDIFF (VBA) DATEPART (VBA) DATESERIAL (VBA) DATEVALUE (WS, VBA) DAY (WS, VBA) FORMAT Dates (VBA) HOUR (WS, VBA) MINUTE (WS, VBA) MONTH (WS, VBA) MONTHNAME (VBA) NOW (WS, VBA) TIMESERIAL (VBA) TIMEVALUE (WS, VBA) WEEKDAY (WS, VBA) WEEKDAYNAME (VBA) YEAR (WS, VBA) Numeric / Mathematical Functions: ABS (WS, VBA) ATN (VBA) COS (WS, VBA) EXP (WS, VBA) FIX (VBA) FORMAT Numbers (VBA) INT (WS, VBA) LOG (WS, VBA) RND (VBA) ROUND (VBA) SGN (VBA) SIN (WS, VBA) TAN (WS, VBA) Financial Functions: DDB (WS, VBA) FV (WS, VBA) IPMT (WS, VBA) IRR (WS, VBA) MIRR (WS, VBA) NPER (WS, VBA) NPV (WS, VBA) PMT (WS, VBA) PPMT (WS, VBA) PV (WS, VBA) RATE (WS, VBA) SLN (WS, VBA) SYD (WS, VBA) Logical Functions: CASE (VBA) IF-THEN-ELSE (VBA) Lookup / Reference Functions: CHOOSE (WS, VBA) SWITCH (WS) Information Functions: ISDATE (VBA) ISERROR (WS, VBA) ISNULL (VBA) ISNUMERIC (VBA) File/Directory Functions: CHDIR (VBA) CHDRIVE (VBA) CURDIR (VBA) DIR (VBA) FILEDATETIME (VBA) FILELEN (VBA) GETATTR (VBA) MKDIR (VBA) SETATTR (VBA) Note: (WS) = Worksheet function, (VBA) = Visual Basic for Applications function 1/56 Data Type Conversion Functions: CBOOL (VBA) CBYTE (VBA) CCUR (VBA) CDATE (VBA) CDBL (VBA) CDEC (VBA) CINT (VBA) CLNG (VBA) CSNG (VBA) CSTR (VBA) CVAR (VBA) VBA Functions String Functions: MS Excel: ASC Function (VBA) In Excel, the ASC function returns the ASCII value of a character or the first character in a string. The syntax for the ASC function is: Asc( string ) string is the specified character to retrieve the AscII value for. If there is more than one character, the function will return the AscII value for the first character and ignore all of the characters after the first. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The ASC function can only be used in VBA code. Here are some examples of what the ASC function would return: Asc ("W") would return 87 Asc ("Wednesday") would return 87 Asc ("x") would return 120 For example: Dim LResult As Integer LResult = Asc ("W") In this example, the variable called LResult would now contain the value 87. MS Excel: CHR Function (VBA) In Excel, the CHR function returns the character based on the ASCII value. The syntax for the CHR function is: Chr( ascii_value ) ascii_value is the ASCII value used to retrieve the character. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) Worksheet Function Example: would return "W" Chr (87) Chr (105) would return "i" VBA Function Example: The CHR function can only be used in VBA code. For example: Dim LResult As String LResult = Chr(87) In this example, the variable called LResult would now contain the value "W". MS Excel: Concatenate with & (WS, VBA) To concatenate multiple strings into a single string in Excel, you can use the "&" operator to separate the string values. The syntax for the "&" operator is: string1 & string2 [& string3 & string_n] Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) 2/56 VBA Functions VBA Function Example: The "&" operator can be used to concatenate strings in VBA code. For example: Dim LValue As String LValue = "Alpha" & "bet" The variable LValue would now contain the value "Alphabet". Frequently Asked Questions Question:For an IF statement in Excel, I want to combine text and a value. For example, I want to put an equation for work hours and pay. If I am paid more than I should be, I want it to read how many hours I owe my boss. But if I work more than I am paid for, I want it to read what my boss owes me (hours*Pay per Hour). I tried the following: =IF(A2<0,"I owe boss" abs(A2) "Hours","Boss owes me" abs(A2)*15 "dollars") Is it possible or do I have to do it in 2 separate cells? (one for text and one for the value) Answer: There are two ways that you can concatenate text and values. The first is by using the & character to concatenate: =IF(A2<0,"I owe boss " & ABS(A2) & " Hours","Boss owes me " & ABS(A2)*15 & " dollars") Or the second method is to use the CONCATENATE function: =IF(A2<0,CONCATENATE("I owe boss ", ABS(A2)," Hours"), CONCATENATE("Boss owes me ", ABS(A2)*15, " dollars")) MS Excel: INSTR Function (VBA) In Excel, the INSTR function returns the position of the first occurrence of a substring in a string. The syntax for the INSTR function is: InStr( [start], string, substring, [compare] ) start is optional. It is the starting position for the search. If this parameter is omitted, the search will begin at position 1. string is the string to search within. substring is the substring that you want to find. compare is optional. It is the type of comparison to perform. It can be one of the following values: VBA Constant Value Explanation vbUseCompareOption -1 Uses option compare vbBinaryCompare 0 Binary comparison vbTextCompare 1 Textual comparison vbDatabaseCompare 2 Comparison based on your database Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The INSTR function can only be used in VBA code. Here are some examples of what the INSTR function would return: InStr(1, "Tech on the Net", "the") would return 9 InStr("Tech on the Net", "the") would return 9 would return 15 InStr(10, "Tech on the Net", "t") For example: Dim LPosition As Integer LPosition = InStr(10, "Tech on the Net", "t") In this example, the variable called LPosition would now contain the value 15. 3/56 VBA Functions MS Excel: INSTRREV Function (VBA) In Excel, the INSTRREV function returns the position of the first occurrence of a string in another string, starting from the end of the string. This is similar to the INSTR function which returns the position of the first occurrence, starting from the beginning of the string. The syntax for the INSTRREV function is: InStrRev ( string, substring [, start [ , compare] ] ) string is the string to search within. substring is the substring that you want to find. start is optional. It is the starting position for the search. If this parameter is omitted, the search will begin at position -1 which is the last character position. compare is optional. It is the type of comparison to perform. It can be one of the following values: VBA Constant Value Explanation vbUseCompareOption -1 Uses option compare vbBinaryCompare 0 Binary comparison vbTextCompare 1 Textual comparison vbDatabaseCompare 2 Comparison based on your database Note: If string2 is not found within string_being_searched, the INSTRREV function will return 0. If string_being_searched is zero-length, the INSTRREV function will return 0. If string_being_searched is null, the INSTRREV function will return null. If start is null, the INSTRREV function will return #Error. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The INSTRREV function can only be used in VBA code. Here are some examples of what the INSTRREV function would return: InStrRev ("alphabet", "a") would return 5 InStrRev ("alphabet", "a", -1) would return 5 InStrRev ("alphabet", "a", 1) would return 1 InStrRev ("alphabet", "a", 2) would return 1 InStrRev ("alphabet", "a", 3) would return 1 InStrRev ("alphabet", "a", 4) would return 1 InStrRev ("alphabet", "a", 5) would return 5 InStrRev ("alphabet", "a", 6) would return 5 InStrRev ("alphabet", "a", 7) would return 5 InStrRev ("alphabet", "a", 8) would return 5 would return 0 InStrRev ("alphabet", "a", 9) For example: Dim LPosition As Integer LPosition = InStrRev ("alphabet", "a") In this example, the variable called LPosition would now contain the value 5. 4/56 VBA Functions MS Excel: LCASE Function (VBA) In Excel, the LCASE function converts a string to lower-case. The syntax for the LCASE function is: LCase( text ) Text is the string that you wish to convert to lower-case. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The LCASE function can only be used in VBA code. Here are some examples of what the LCASE function would return: LCase("ALPHABET") would return "alphabet" LCase("Tech on the Net") would return "tech on the net" LCase("124ABC") would return "124abc" For example: Dim LResult As String LResult = LCase("This is a TEST") In this example, the variable called LResult would now contain the value "this is a test". MS Excel: LEFT Function (WS, VBA) In Excel, the LEFT function allows you to extract a substring from a string, starting from the left-most character. The syntax for the LEFT function is: LEFT( text, [number_of_characters] ) text is the string that you wish to extract from. number_of_characters is optional. It indicates the number of characters that you wish to extract starting from the left-most character. If this parameter is omitted, only 1 character is returned. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The LEFT function can also be used in VBA code. For example: Dim LResult As String LResult = Left("Alphabet",3) The variable LResult would now contain the value of "Alp". MS Excel: LEN Function (WS, VBA) In Excel, the LEN function returns the length of the specified string. The syntax for the LEN function is: LEN( text ) text is the string to return the length for. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The LEN function can also be used in VBA code. For example: 5/56 VBA Functions Dim LResult As Long LResult = Len ("www.techonthenet.com") In this example, the variable called LResult would now contain the value 20. MS Excel: LTRIM Function (VBA) In Excel, the LTRIM function removes leading spaces from a string. The syntax for the LTRIM function is: LTRIM( text ) text is the string that you wish to remove leading spaces from. Applies To: Excel, 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The LTRIM function can only be used in VBA code. Here are some examples of what the LTRIM function would return: LTRIM(" Tech on the Net") would return "Tech on the Net" LTRIM(" Alphabet") would return "Alphabet" LTRIM(" Alphabet ") would return "Alphabet " For example: Dim LResult As String LResult = LTrim(" Alphabet ") The variable LResult would now contain the value of "Alphabet ". MS Excel: MID Function (WS, VBA) In Excel, the MID function extracts a substring from a string (starting at any position). The syntax for the MID function is: MID( text, start_position, number_of_characters ) text is the string that you wish to extract from. start_position indicates the position in the string that you will begin extracting from. The first position in the string is 1. number_of_characters indicates the number of characters that you wish to extract. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The MID function can also be used in VBA code. For example: Dim LResult As String LResult = Mid("Alphabet", 5, 2) The variable LResult would now contain the value of "ab". MS Excel: REPLACE Function (VBA) In Excel, the REPLACE function replaces a sequence of characters in a string with another set of characters. Please note that the worksheet version of the REPLACE function has different syntax. The syntax for the REPLACE function is: Replace ( string1, find, replacement, [start, [count, [compare]]] ) string1 is the string to replace a sequence of characters with another set of characters. find is the string that will be searched for in string1. replacement will replace find in string1. 6/56 VBA Functions start is optional. This is the position in string1 to begin the search. If this parameter is omitted, the REPLACE function will begin the search at position 1. count is optional. This is the number of occurrences to replace. If this parameter is omitted, the REPLACE function will replace all occurrences offind with replacement. compare is optional. This can be one of the following values: Parameter Value Description vbBinaryCompare Binary comparison vbTextCompare Textual comparison vbDatabaseCompare Performs a comparison based on information in your database Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The REPLACE function can be used in VBA code. Here are some examples of what the REPLACE function would return: Replace("alphabet", "bet", "hydro") would return "alphahydro" Replace ("alphabet", "a", "e") would return "elphebet" Replace("alphabet", "a", "e", 2) would return "lphebet" would return "elphabet" Replace("alphabet", "a", "e", 1, 1) For example: Dim LResult As String LResult = Replace("alphabet", "a", "e") In this example, the variable called LResult would now contain the value "elphebet". MS Excel: RIGHT Function (WS, VBA) In Excel, the RIGHT function extracts a substring from a string starting from the right-most character. The syntax for the RIGHT function is: RIGHT( text, [number_of_characters] ) text is the string that you wish to extract from. number_of_characters is optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The RIGHT function can also be used in VBA code. For example: Dim LResult As String LResult = Right("Alphabet",3) The variable LResult would now contain the value of "bet". MS Excel: RTRIM Function (VBA) In Excel, the RTRIM function removes trailing spaces from a string. The syntax for the RTRIM function is: RTrim( text ) text is the string that you wish to remove trailing spaces from. 7/56 VBA Functions Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The RTRIM function can only be used in VBA code. Here are some examples of what the RTRIM function would return: RTrim("Tech on the Net ") would return "Tech on the Net" RTrim(" Alphabet ") would return " Alphabet" For example: Dim LResult As String LResult = RTrim(" Alphabet ") The variable LResult would now contain the value of " Alphabet". MS Excel: SPACE Function (VBA) In Excel, the SPACE function returns a string with a specified number of spaces. The syntax for the SPACE function is: Space( number ) number is the number of spaces to be returned. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The SPACE function can only be used in VBA code. Here are some examples of what the SPACE function would return: Space(3) would return " " would return " " Space(7) For example: Dim LResult As String LResult = Space(5) In this example, the variable called LResult would now contain the value " MS Excel: STR Function (VBA) ". In Excel, the STR function returns a string representation of a number. The syntax for the STR function is: Str( number ) number is the value to convert to a string. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The STR function can only be used in VBA code. Here are some examples of what the STR function would return: STR(12) would return "12" would return "450" STR(450) For example: Dim LResult As String LResult = Str(16) 8/56 VBA Functions In this example, the variable called LResult would now contain the value "16". MS Excel: STRCONV Function (VBA) In Excel, the STRCONV function returns a string converted as specified. The syntax for the STRCONV function is: StrConv ( text, conversion, LCID ) text is the string that you wish to convert. conversion is the type of conversion to perform. The following is a list of valid parameters for conversion. Parameter Value Description vbUpperCase 1 Converts the string to all uppercase. vbLowerCase 2 Converts the string to all lowercase. vbProperCase 3 Converts the first letter to every word to uppercase. All other characters are left as lowercase. This option is similar to the InitCap function in Oracle. vbUnicode 64 Converts the string to Unicode. vbFromUnicode 128 Converts the string from Unicode to the default code page of the system. LCID is optional. If this parameter is omitted, the STRCONV function assumes the system LocaleID. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The STRCONV function can only be used in VBA code. Here are some examples of what the STRCONV function would return: StrConv("tech on the net", 1) would return "TECH ON THE NET" StrConv("TECH ON THE NET", 2) would return "tech on the net" StrConv("TECH ON THE NET", 3) would return "Tech On The Net" For example: Dim LResult As String LResult = StrConv("TECH ON THE NET", vbProperCase) In this example, the variable called LResult would now contain the value "Tech On The Net". MS Excel: TRIM Function (WS, VBA) In Excel, the TRIM function returns a text value with the leading and trailing spaces removed. The syntax for the TRIM function is: TRIM( text ) text is the text value to remove the leading and trailing spaces from. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The TRIM function can also be used in VBA code. For example: Dim LResult As String LResult = Trim (" Alphabet ") The variable LResult would now contain the value of "Alphabet". MS Excel: UCASE Function (VBA) In Excel, the UCASE function converts a string to all upper-case. 9/56 VBA Functions The syntax for the UCASE function is: UCase( text ) text is the string that you wish to convert to upper-case. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The UCASE function can only be used in VBA code. Here are some examples of what the UCASE function would return: UCase("Tech on the Net") would return "TECH ON THE NET" UCase("Alphabet") would return "ALPHABET" For example: Dim LResult As String LResult = UCase("This is a TEST") In this example, the variable called LResult would now contain the value "THIS IS A TEST". MS Excel: VAL Function (VBA) In Excel, the VAL function accepts a string as input and returns the numbers found in that string. The syntax for the VAL function is: Val( string ) string is a string expression. Note: The VAL function will stop reading the string once it encounters the first non-numeric character. This does not include spaces. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The VAL function can only be used in VBA code. Here are some examples of what the VAL function would return: Val("10 Main Street") would return 10 Val("34 10 Main Street") would return 3410 Val(" 34 10 Main Street") would return 3410 Val(" 34 - 10 Main Street") would return 34 would return 75 Val("075") For example: Dim LNumber As Double LNumber = Val("56.2 tables") In this example, the variable called LNumber would now contain the value of 56.2. 10/56 VBA Functions Numeric / Mathematical Functions: MS Excel: ABS Function (WS, VBA) In Excel, the ABS function returns the absolute value of a number. The syntax for the ABS function is: ABS( number ) number is a numeric value. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The ABS function can also be used in VBA code. For example: Dim LNumber As Double LNumber = Abs (-210.6) In this example, the variable called LNumber would now contain the value of 210.6. MS Excel: ATN Function (VBA) In Excel, the ATN function returns the arctangent of a number. The syntax for the ATN function is: Atn( number ) number is a numeric expression. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The ATN function can only be used in VBA code. Here are some examples of what the ATN function would return: Atn(2) would return 1.10714871779409 Atn(2.51) would return 1.19166451926354 Atn(-3.25) would return -1.27229739520872 For example: Dim LNumber As Double LNumber = Atn(210) In this example, the variable called LNumber would now contain the value of 1.56603445802574. MS Excel: COS Function (WS, VBA) In Excel, the COS function returns the cosine of an angle. The syntax for the COS function is: COS( number ) number is a numeric value. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The COS function can also be used in VBA code. For example: Dim LNumber As Double LNumber = Cos(210) 11/56 VBA Functions In this example, the variable called LNumber would now contain the value of -0.883877473. MS Excel: EXP Function (WS, VBA) In Excel, the EXP function returns e raised to the nth power, where e = 2.71828183. The syntax for the EXP function is: EXP( number ) number is the power to raise e to. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The EXP function can also be used in VBA code. For example: Dim LNumber As Double LNumber = Exp(3) In this example, the variable called LNumber would now contain the value of 20.08553692. MS Excel: FIX Function (VBA) In Excel, the FIX function returns the integer portion of a number. The syntax for the FIX function is: Fix( expression ) expression is a numeric expression whose integer portion is returned. Note: If the expression is negative, the FIX function will return the first negative number that is greater than or equal to the expression. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The FIX function can only be used in VBA code. Here are some examples of what the FIX function would return: Fix(210.67) would return 210 Fix(2.98) would return 2 would return -2 Fix(-2.98) For example: Dim LNumber As Double LNumber = Fix(210.67) In this example, the variable called LNumber would now contain the value of 210. MS Excel: FORMAT Function with Numbers (VBA) In Excel, the FORMAT function takes an expression and returns it as a formatted string. The syntax for the FORMAT function is: Format ( expression, [ format ] ) expression is the value to format. format is optional. It is the format to apply to the expression. You can either define your own format or use one of the named formats that Excel has predefined such as: Format General Number Explanation Displays a number without thousand separators. 12/56 VBA Functions Currency Displays thousand separators as well as two decimal places. Fixed Displays at least one digit to the left of the decimal place and two digits to the right of the decimal place. Standard Displays the thousand separators, at least one digit to the left of the decimal place, and two digits to the right of the decimal place. Percent Displays a percent value - that is, a number multiplied by 100 with a percent sign. Displays two digits to the right of the decimal place. Scientific Scientific notation. Yes/No Displays No if the number is 0. Displays Yes if the number is not 0. True/False Displays True if the number is 0. Displays False if the number is not 0. On/Off Displays Off if the number is 0. Displays On is the number is not 0. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The FORMAT function can only be used in VBA code. Here are some examples of what the FORMAT function would return: Format(210.6, "#,##0.00") would return '210.60' Format(210.6, "Standard") would return '210.60' Format(0.981, "Percent") would return '98.10%' Format(1267.5, "Currency") would return '$1,267.50' For example: Dim LValue As String LValue = Format(0.981, "Percent") In this example, the variable called LValue would now contain the value of '98.10%'. MS Excel: INT Function (WS, VBA) In Excel, the INT function returns the integer portion of a number. The syntax for the INT function is: INT( expression ) expression is a numeric expression whose integer portion is returned. Note: If the expression is negative, the INT function will return the first negative number that is less than or equal to the expression. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The INT function can also be used in VBA code. For example: Dim LNumber As Double LNumber = Int(210.67) In this example, the variable called LNumber would now contain the value of 210. 13/56 VBA Functions MS Excel: LOG Function (WS, VBA) In Excel, the LOG function returns the logarithm of a number to a specified base. The syntax for the LOG function is: LOG( number, [base] ) number is a numeric value that must be greater than 0. base is optional. This is the base to use to calculate the logarithm of a number. If this parameter is omitted, the LOG function will use a base of 10. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The LOG function can also be used in VBA code. However in VBA, the LOG function returns the natural logarithm of a number. The syntax for the LOG function in VBA is: Log( number ) number is a numeric value that must be greater than 0. For example: Dim LResult As Double LResult = Log(20) In this example, the variable called LResult would now contain the value 2.995732274. MS Excel: RND Function (VBA) In Excel, the RND function allows you to generate a random number (integer value). You can specify the random number to be a value between 2 user-specified numbers. The syntax for the RND function is: Int ((upperbound - lowerbound + 1) * Rnd + lowerbound) upperbound is the highest value that the random number can be. lowerbound is the lowest value that the random number can be. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The RND function can only be used in VBA code. Here are some examples of what the RND function would return: Int ((6 - 1 + 1) * Rnd + 1) would return a random number between 1 and 6 Int ((200 - 150 + 1) * Rnd + 150) would return a random number between 150 and 200 Int ((999 - 100 + 1) * Rnd + 100) would return a random number between 100 and 999 For example: Dim LRandomNumber As Integer LRandomNumber = Int ((300 - 200 + 1) * Rnd + 200) In this example, the variable called LRandomNumber would now contain a random number between 200 and 300. MS Excel: ROUND Function (VBA) In Excel, the ROUND function returns a number rounded to a specified number of digits. Please note that the VBA version of the ROUND functionhas different syntax. The syntax for the ROUND function is: Round ( expression, [decimal_places] ) 14/56 VBA Functions expression is a numeric expression that is to be rounded. decimal_places is optional. It is the number of decimal places to round the expression to. If this parameter is omitted, then the ROUND function will return an integer. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: In Excel's VBA environment, the ROUND function returns a number rounded to a specified number of decimal places. However, the ROUND function behaves a little peculiar, so before using this function, please read the following: The ROUND function utilizes round-to-even logic. If the expression that you are rounding ends with a 5, the ROUND function will round the expression so that the last digit is an even number. For example: Round(12.55, 1) would return 12.6 (rounds up) Round(12.65, 1) would return 12.6 (rounds down) Round(12.75, 1) would return 12.8 (rounds up) In these cases, the last digit after rounding is always an even number. So, be sure to only use the ROUND function if this is your desired result. The ROUND function can be used in VBA code. Here are some examples of what the ROUND function would return: Round(210.67, 1) would return 210.7 Round(210.67, 0) would return 211 Round(210.67) would return 211 For example: Dim LNumber As Double LNumber = Round(210.67, 1) In this example, the variable called LNumber would now contain the value of 210.7. Frequently Asked Questions Question: I read your explanation of how the ROUND function works in VBA using the round-to-even logic. However, I really need to round some values in the traditional sense (where 5 always rounds up). How can I do this? Answer: You could always use the following logic: If you wanted to round 12.65 to 1 decimal place in the traditional sense (where 12.65 rounded to 1 decimal place is 12.7, instead of 12.6), try adding 0.000001 to your number before applying the ROUND function: Round(12.45+0.000001,1) By adding the 0.000001, the expression that you are rounding will end in 1, instead of 5...causing the ROUND function to round in the traditional way. And the 0.000001 does not significantly affect the value of your expression so you shouldn't introduce any calculation errors. MS Excel: SGN Function (VBA) In Excel, the SGN function returns the sign of a number (represented as an integer). The syntax for the SGN function is: Sgn ( number ) number is the the number to return the sign for. Note: If number is greater than zero, the SGN function will return 1. If number is equal to zero, the SGN function will return 0. If number is less than zero, the SGN function will return -1. 15/56 VBA Functions Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The SGN function can only be used in VBA code. Here are some examples of what the SGN function would return: Sgn(-123.67) would return -1 Sgn(0) would return 0 Sgn(123.67) would return 1 For example: Dim LResult As Integer LResult = Sgn(56) In this example, the variable called LResult would now contain the value of 1. MS Excel: SIN Function (WS, VBA) In Excel, the SIN function returns the sine of an angle. The syntax for the SIN function is: SIN( number ) number is a numeric value. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The SIN function can also be used in VBA code. For example: Dim LNumber As Double LNumber = Sin(2) In this example, the variable called LNumber would now contain the value of 0.909297427. MS Excel: TAN Function (WS, VBA) In Excel, the TAN function returns the tangent of an angle. The syntax for the TAN function is: TAN( number ) number is a numeric value. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The TAN function can also be used in VBA code. For example: Dim LNumber As Double LNumber = Tan(2) In this example, the variable called LNumber would now contain the value of -2.185039863. 16/56 VBA Functions Logical Functions MS Excel: CASE Statement (VBA) In Excel, the CASE statement has the functionality of an IF-THEN-ELSE statement. The syntax for the CASE statement is: Select Case test_expression Case condition_1 result_1 Case condition_2 result_2 ... Case condition_n result_n Case Else result_else End Select test_expression is a string or numeric value. It is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ... condition_n) condition_1 to condition_n are evaluated in the order listed. Once a condition is found to be true, the CASE statement will execute the corresponding code and not evaluate the conditions any further. result_1 to result_n is the code that is executed once a condition is found to be true. Note: If no condition is met, then the Else portion of the CASE statement will be executed. It is important to note that the Else portion is optional. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The Case statement can only be used in VBA code. Let's take a look at a simple example: Select Case LRegion Case "N" LRegionName = "North" Case "S" LRegionName = "South" Case "E" LRegionName = "East" Case "W" LRegionName = "West" End Select You can also use the To keyword to specify a range of values. For example: Select Case LNumber Case 1 To 10 LRegionName = "North" Case 11 To 20 LRegionName = "South" Case 21 To 30 LRegionName = "East" 17/56 VBA Functions Case Else LRegionName = "West" End Select You can also comma delimit values. For example: Select Case LNumber Case 1, 2 LRegionName = "North" Case 3, 4, 5 LRegionName = "South" Case 6 LRegionName = "East" Case 7, 11 LRegionName = "West" End Select And finally, you can also use the Is keyword to compare values. For example: Select Case LNumber Case Is < 100 LRegionName = "North" Case Is < 200 LRegionName = "South" Case Is < 300 LRegionName = "East" Case Else LRegionName = "West" End Select MS Excel: IF-THEN-ELSE Statement (VBA) In Excel, the IF-THEN-ELSE statement can only be used in VBA code. The syntax for the IF-THEN-ELSE statement is: If condition_1 Then result_1 ElseIf condition_2 Then result_2 ... ElseIf condition_n Then result_n Else result_else End If condition_1 to condition_n are evaluated in the order listed. Once a condition is found to be true, the IFTHEN-ELSE statement will execute the corresponding code and not evaluate the conditions any further. result_1 to result_n is the code that is executed once a condition is found to be true. Note: If no condition is met, then the Else portion of the IF-THEN-ELSE statement will be executed. It is important to note that the ElseIf and Else portions are optional. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA statement (VBA) 18/56 VBA Functions VBA Statement Example: The IF-THEN-ELSE statement can only be used in VBA code. First, let's take a look at a simple example. If LRegion ="N" Then LRegionName = "North" End If Next, let's take a look at an example that uses ElseIf. If LRegion ="N" Then LRegionName = "North" ElseIf LRegion = "S" Then LRegionName = "South" ElseIf LRegion = "E" Then LRegionName = "East" ElseIf LRegion = "W" Then LRegionName = "West" End If Finally, let's take a look at an example that uses Else. If LRegion ="N" Then LRegionName = "North" ElseIf LRegion = "S" Then LRegionName = "South" ElseIf LRegion = "E" Then LRegionName = "East" Else LRegionName = "West" End If 19/56 VBA Functions Information Functions: MS Excel: ISDATE Function (VBA) In Excel, the ISDATE function returns TRUE if the expression is a valid date. Otherwise, it returns FALSE. The syntax for the ISDATE function is: IsDate( expression ) expression is a variant. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The ISDATE function can only be used in VBA code. Here are some examples of what the ISDATE function would return: ISDATE("1/3/2004") would return TRUE ISDATE("Tech on the Net") would return FALSE ISDATE("January 3, 2004") would return TRUE For example: Dim LValue As Boolean LValue = IsDate("Tech on the Net") In this example, the variable called LValue would contain FALSE as a value. MS Excel: ISERROR Function (WS, VBA) In Excel, the ISERROR function can be used to check for error values. The syntax for the ISERROR function is: ISERROR( value ) value is the value that you want to test. If value is an error value (#N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME? or #NULL), this function will return TRUE. Otherwise, it will return FALSE. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The ISERROR function can also be used in VBA code. For example: Dim LReturnValue as Boolean LReturnValue = IsError(CustomFunction()) In this example, the variable called LReturnValue would now contain whether the call to the CustomFunction resulted in an error. Frequently Asked Questions Question: Can you give me specific examples of when and how the ISERROR function is used. Specifically, in a worksheet why would I use this function instead of just running down a column or across a row to look for the errors? Answer: Often times your spreadsheet contains a large amount of formulas which will not properly calculate when an error is encountered. The ISERROR function, in combination with the If function, can be used to default a cell's value when an error is occurred. This allows your formulas to evaluate properly without your intervention. For example, you may encounter a scenario below: 20/56 VBA Functions Instead of using the formula: =B4/C4 You could use the ISERROR function as follows: =IF(ISERROR(B4/C4),0,B4/C4) In this case, the ISERROR function would allow you to return a 0, when an error was encounter such as a "divide by 0 error". Now all of your formulas will still work. MS Excel: ISNULL Function (VBA) In Excel, the ISNULL function returns TRUE if the expression is a null value. Otherwise, it returns FALSE. The syntax for the ISNULL function is: IsNull( expression ) expression is a variant that contains a string or numeric value. Applies To: Excel 20010, Excel 2003, Excel XP, Excel 2000 21/56 VBA Functions Type of Function: VBA function (VBA) VBA Function Example: The ISNULL function can only be used in VBA code. Here are some examples of what the ISNULL function would return: IsNull(null) would return TRUE IsNull("Tech on the Net") would return FALSE For example: Dim LValue As Boolean LValue = IsNull("Tech on the Net") In this example, the variable called LValue would contain FALSE as a value. MS Excel: ISNUMERIC Function (VBA) In Excel, the ISNUMERIC function returns TRUE if the expression is a valid number. Otherwise, it returns FALSE. The syntax for the ISNUMERIC function is: IsNumeric( expression ) expression is a variant. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The ISNUMERIC function can only be used in VBA code. Here are some examples of what the ISNUMERIC function would return: IsNumeric(786) would return TRUE IsNumeric("Tech on the Net") would return FALSE IsNumeric("234") would return TRUE would return FALSE IsNumeric("123abc") For example: Dim LValue As Boolean LValue = IsNumeric("Tech on the Net") In this example, the variable called LValue would contain FALSE as a value. 22/56 VBA Functions Date & Time Functions MS Excel: DATE Function (VBA) In Excel, the DATE function returns the current system date. Please note that the worksheet version of the DATE function has different syntax. The syntax for the DATE function is: Date() Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The DATE function can only be used in VBA code. Date() would return a value such as '22/11/2003' For example: Dim LDate As String LDate = Date In this example, the variable called LDate would now contain the current system date. MS Excel: DATEADD Function (VBA) In Excel, the DATEADD function returns a date after which a certain time/date interval has been added. The syntax for the DATEADD function is: DateAdd ( interval, number, date ) interval is the time/date interval that you wish to add. It can be one of the following values: Value Explanation yyyy Year q Quarter m Month y Day of the year d Day w Weekday ww Week h Hour n Minute s Second number is the number of intervals that you wish to add. date is the date to which the interval should be added. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The DATEADD function can only be used in VBA code. Here are some examples of what the DATEADD function would return: DateAdd("yyyy", 3, "22/11/2003") would return '22/11/2006' DateAdd("q", 2, "22/11/2003") would return '22/05/2004' 23/56 VBA Functions DateAdd("m", 5, "22/11/2003") would return '22/04/2004' DateAdd("n", 51, "22/11/2003 10:31:58 AM") would return '22/11/2003 11:22:58 AM' would return '22/11/2002' DateAdd("yyyy", -1, "22/11/2003") For example: Dim LDate As Date LDate = DateAdd("s", 53, "22/11/2003 10:31:58 AM") In this example, the variable called LDate would now contain the value of '22/11/2003 10:32:51 AM'. MS Excel: DATEDIFF Function (VBA) In Excel, the DATEDIFF function returns the difference between two date values, based on the interval specified. The syntax for the DATEDIFF function is: DateDiff( interval, date1, date2, [firstdayofweek], [firstweekofyear] ) interval is the interval of time to use to calculate the difference between date1 and date2. Below is a list of valid interval values. Interval Explanation yyyy Year q Quarter m Month y Day of year d Day w Weekday ww Week h Hour n Minute s Second date1 and date2 are the two dates to calculate the difference between. firstdayofweek is optional. It is a constant that specifies the first day of the week. If this parameter is omitted, Excel assumes that Sunday is the first day of the week. firstweekofyear is optional. It is a constant that specifies the first week of the year. If this parameter is omitted, Excel assumes that the week containing Jan 1st is the first week of the year. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The DATEDIFF function can only be used in VBA code. Here are some examples of what the DATEDIFF function would return: DateDiff("yyyy", "22/11/2003", "22/11/2013") would return 10 DateDiff("q", "22/11/2003", "22/11/2013") would return 40 DateDiff("m", "22/11/2011", "1/1/2012") would return 2 For example, you could use the DATEDIFF function in VBA code and create the following function: Function TestDates (pDate1 as Date, pDate2 as Date) as Long 24/56 VBA Functions TestDates = DateDiff("d", pDate1, pDate2) End Function MS Excel: DATEPART Function (VBA) In Excel, the DATEPART function returns a specified part of a given date. The syntax for the DATEPART function is: DatePart( interval, date, [firstdayofweek], [firstweekofyear] ) interval is the interval of time that you wish to return. This parameter can be any one of the following valid interval values: Interval Explanation yyyy Year q Quarter m Month y Day of year d Day w Weekday ww Week h Hour n Minute s Second date is the date value that you wish to evaluate. firstdayofweek is optional. It is a constant that specifies the first day of the week. If this parameter is omitted, Excel assumes that Sunday is the first day of the week. This parameter can be one of the following values: Constant Value Explanation vbUseSystem 0 Use the NLS API setting vbSunday 1 Sunday (default) vbMonday 2 Monday vbTuesday 3 Tuesday vbWednesday 4 Wednesday vbThursday 5 Thursday vbFriday 6 Friday vbSaturday 7 Saturday firstweekofyear is optional. It is a constant that specifies the first week of the year. If this parameter is omitted, Excel assumes that the week containing Jan 1st is the first week of the year. This parameter can be one of the following values: Constant Value Explanation vbUseSystem 0 Use the NSL API setting vbFirstJan1 1 Use the first week that includes Jan 1st (default) vbFirstFourDays 2 Use the first week in the year that has at least 4 days vbFirstFullWeek 3 Use the first full week of the year 25/56 VBA Functions Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The DATEPART function can only be used in VBA code. Here are some examples of what the DATEPART function would return: DatePart("yyyy", "15/10/2012") would return 2012 DatePart("m", "15/10/2012") would return 10 DatePart("d", "15/10/2012") would return 15 For example: Dim LValue As Integer LValue = DatePart("d", "15/10/2012") In this example, the variable called LValue would now contain the value of 15. MS Excel: DATESERIAL Function (VBA) In Excel, the DATESERIAL function returns a date given a year, month, and day value. The syntax for the DATESERIAL function is: DateSerial( year, month, day ) year is a numeric value between 100 and 9999 that represents the year value of the date. month is a numeric value that represents the month value of the date. day is a numeric value that represents the day value of the date. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The DATESERIAL function can only be used in VBA code. Here are some examples of what the DATESERIAL function would return: DateSerial(2004, 6, 30) would return "6/30/2004" DateSerial(2004-1, 6, 30) would return "6/30/2003" DateSerial(2004, 6-2, 14) would return "4/14/2004" For example: Dim LDate As Date LDate = DateSerial(2004, 5, 31) In this example, the variable called LDate would now contain the value of "5/31/2004". MS Excel: DATEVALUE Function (WS, VBA) In Excel, the DATEVALUE function returns the serial number of a date. It is a worksheet function (WS) and VBA function (VBA). The syntax for the DATEVALUE function is: DATEVALUE( date ) date is a string representation of a date. Applies To: Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The DATEVALUE function can be used in VBA code. For example: 26/56 VBA Functions Dim LDate As Date LDate = DateValue("May 15, 2012") In this example, the variable called LDate would now contain the value of 5/15/2012. MS Excel: DAY Function (WS, VBA) In Excel, the DAY function returns the day of the month (a number from 1 to 31) given a date value. The syntax for the DAY function is: DAY( date_value ) date_value is a valid date. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The DAY function can be used in VBA code. For example: Dim LDay As Integer LDay = Day("12/31/2011") In this example, the variable called LDay would now contain the value of 31. MS Excel: FORMAT Function with Dates (VBA) In Excel, the FORMAT function takes an expression and returns it as a formatted string. The syntax for the FORMAT function is: Format ( expression, [ format, [ firstdayofweek, [firstweekofyear] ] ] ) expression is the value to format. format is optional. It is the format to apply to the expression. You can either define your own format or use one of the named formats that Excel has predefined such as: Format Explanation General Date Displays date based on your system settings Long Date Displays date based on your system's long date setting Medium Date Displays date based on your system's medium date setting Short Date Displays date based on your system's short date setting Long Time Displays time based on your system's long time setting Medium Time Displays time based on your system's medium time setting Short Time Displays time based on your system's short time setting firstdayofweek is optional. It is a value that specifies the first day of the week. If this parameter is omitted, the FORMAT function assumes that Sunday is the first day of the week. This parameter can be one of the following values: Constant Value Explanation vbUseSystem 0 Uses the NLS API setting VbSunday 1 Sunday (default, if parameter is omitted) vbMonday 2 Monday vbTuesday 3 Tuesday vbWednesday 4 Wednesday 27/56 VBA Functions vbThursday 5 Thursday vbFriday 6 Friday vbSaturday 7 Saturday firstweekofyear is optional. It is a value that specifies the first week of the year. If this parameter is omitted, the FORMAT function assumes that the week that contains January 1 is the first week of the year. This parameter can be one of the following values: Constant Value Explanation vbUseSystem 0 Uses the NLS API setting vbFirstJan1 1 The week that contains January 1. vbFirstFourDays 2 The first week that has at least 4 days in the year. vbFirstFullWeek 3 The first full week of the year. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The FORMAT function can only be used in VBA code. Here are some examples of what the FORMAT function would return: Format(#17/04/2004#, "Short Date") would return '17/04/2004' Format(#17/04/2004#, "Long Date") would return 'April 17, 2004' Format(#17/04/2004#, "yyyy/mm/dd") would return '2004/04/17' For example: Dim LValue As String LValue = Format(Date, "yyyy/mm/dd") In this example, the variable called LValue would now contain the date formatted as yyyy/mm/dd. MS Excel: HOUR Function (WS, VBA) In Excel, the HOUR function returns the hour of a time value (from 0 to 23). The syntax for the HOUR function is: Hour( serial_number ) serial_number is the time value to extract the hour from. It may be expressed as a string value, a decimal number, or the result of a formula. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The HOUR function can also be used in VBA code. For example: Dim LHour As Integer LHour = Hour("10:42:58 PM") In this example, the variable called LHour would now contain the value of 22. MS Excel: MINUTE Function (WS, VBA) In Excel, the MINUTE function returns the minute of a time value (from 0 to 59). The syntax for the MINUTE function is: MINUTE( serial_number ) 28/56 VBA Functions serial_number is the time value to extract the minute from. It may be expressed as a string value, a decimal number, or the result of a formula. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The MINUTE function can be used in VBA code. For example: Dim LMinute As Integer LMinute = Minute("10:13:58 AM") In this example, the variable called LMinute would now contain the value of 13. MS Excel: MONTH Function (WS, VBA) In Excel, the MONTH function returns the month (a number from 1 to 12) given a date value. The syntax for the MONTH function is: MONTH( date_value ) date_value is a valid date. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The MONTH function can also be used in VBA code. For example: Dim LMonth As Integer LMonth = Month("12/31/2001") In this example, the variable called LMonth would now contain the value of 12. MS Excel: MONTHNAME Function (VBA) In Excel, the MONTHNAME function returns a string representing the month given a number from 1 to 12. The syntax for the MONTHNAME function is: MonthName( number, [ abbreviate ] ) number is a value from 1 to 12, representing the month. abbreviate is optional. This parameter accepts a boolean value, either TRUE or FALSE. If this parameter is set to TRUE, it means that the month name is abbreviated. If this parameter is set to FALSE, the month name is not abbreviated. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The MONTHNAME function can only be used in VBA code. Here are some examples of what the MONTHNAME function would return: MonthName(3) would return 'March' MonthName(3, TRUE) would return 'Mar' MonthName(7, FALSE) would return 'July' For example: Dim LValue As String LValue = MonthName(3, TRUE) In this example, the variable called LValue would now contain the value of 'Mar'. MS Excel: NOW Function (WS, VBA) 29/56 VBA Functions In Excel, the NOW function returns the current system date and time. This function will refresh the date/time value whenever the worksheet recalculates. The syntax for the NOW function is: NOW() Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The NOW function can also be used in VBA code. For example: Dim LValue As Date LValue = Now In this example, the variable called LValue would now contain the current system date and time. MS Excel: TIMESERIAL Function (VBA) In Excel, the TIMESERIAL function returns a time given an hour, minute, and second value. The syntax for the TIMESERIAL function is: TimeSerial( hour, minute, second ) hour is a numeric value between 0 and 23 that represents the hour value of the time. minute is a numeric value that represents the minute value of the time. second is a numeric value that represents the second value of the time. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The TIMESERIAL function can only be used in VBA code. Here are some examples of what the TIMESERIAL function would return: TimeSerial(14, 6, 30) would return 2:06:30 PM TimeSerial(20 - 8, 6, 30) would return 12:06:30 PM TimeSerial(8, 6-2, 14) would return 8:04:14 AM would return 6:45:50 AM TimeSerial(7, -15, 50) For example: Dim LTime As Date LTime = TimeSerial (23, 5, 31) In this example, the variable called LTime would now contain the value of "11:05:31 PM". MS Excel: TIMEVALUE Function (WS, VBA) In Excel, the TIMEVALUE function returns the serial number of a time. The syntax for the TIMEVALUE function is: TIMEVALUE( time_value ) time_value is a string representation of a time. This can not be a date/time value (it MUST be a string). Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The TIMEVALUE function can also be used in VBA code. For example: Dim LTime As Date 30/56 VBA Functions LTime = TimeValue("18:30:12") In this example, the variable called LTime would now contain the value of 6:30:12 PM. MS Excel: WEEKDAY Function (WS, VBA) In Excel, the WEEKDAY function returns a number representing the day of the week, given a date value. The syntax for the WEEKDAY function is: WEEKDAY( serial_number, [return_value] ) serial_number is a date expressed as a serial number or a date in quotation marks. return_value is optional. It is the option used to display the result. It can be any of the following values: Value Explanation 1 Returns a number from 1 (Sunday) to 7 (Saturday). This is the default if parameter is omitted. 2 Returns a number from 1 (Monday) to 7 (Sunday). 3 Returns a number from 0 (Monday) to 6 (Sunday). If this parameter is omitted, the WEEKDAY function assumes that the return_value is set to 1. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The WEEKDAY function can also be used in VBA code. For example: Dim LWeekday As Integer LWeekday = Weekday("12/31/2001", vbSunday) In this example, the variable called LWeekday would now contain the value of 2. Frequently Asked Questions Question: Is there a LIKE function in Excel similar to the one in Access? I'm trying to write a formula equivalent to the following: =if(D14 like "*Saturday*", Now()+2, Now()+1) Where cell D14 is a date value formatted as Saturday, August 27, 2005. Answer: Since your value in cell D14 is a date value, you can use the WEEKDAY function to determine which day of the week it is. In this case, you are looking for a Saturday. The WEEKDAY function will return a value of 7 when the date falls on a Saturday. Try using the following formula: =if(Weekday(D14)=7,Now()+2,Now()+1) MS Excel: WEEKDAYNAME Function (VBA) In Excel, the WEEKDAYNAME function returns a string representing the day of the week given a number from 1 to 7. The syntax for the WEEKDAYNAME function is: WeekdayName( number, [abbreviate], [firstdayofweek] ) number is a value from 1 to 7, representing a day of the week. abbreviate is optional. This parameter accepts a boolean value, either TRUE or FALSE. If this parameter is set to TRUE, it means that the weekday name is abbreviated. If this parameter is set to FALSE, the weekday name is not abbreviated. firstdayofweek is optional. It determines what day is to be the first day of the week. It can be any of the following values: Constant Value Explanation vbUseSystem 0 Use the NLS API settings vbSunday Sunday (default used) 1 31/56 VBA Functions vbMonday 2 Monday vbTuesday 3 Tuesday vbWednesday 4 Wednesday vbThursday 5 Thursday vbFriday 6 Friday vbSaturday 7 Saturday If this parameter is omitted, the WEEKDAYNAME function assumes that the first day of the week is Sunday. Please note that if you use the WEEKDAYNAME function in a query, you'll have to use the numeric value (ie: 0 to 7) for the firstdayofweek parameter. You can only use the constant equivalent (ie: vbSunday to vbSaturday) in VBA code. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The WEEKDAYNAME function can only be used in VBA code. Here are some examples of what the WEEKDAYNAME function would return: WeekdayName(3) would return 'Tuesday' WeekdayName(3, TRUE) would return 'Tue' WeekdayName(3, TRUE, vbMonday) would return 'Wed' would return 'Wed' WeekdayName(3, TRUE, 2) For example: Dim LValue As String LValue = WeekdayName(3, TRUE, vbMonday) In this example, the variable called LValue would now contain the value of 'Wed'. MS Excel: YEAR Function (WS, VBA) In Excel, the YEAR function returns a four-digit year (a number from 1900 to 9999) given a date value. The syntax for the YEAR function is: YEAR( date_value ) date_value is a valid date. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) VBA Function Example: The YEAR function can also be used in VBA code. For example: Dim LYear As Integer LYear = Year("12/03/2001") In this example, the variable called LYear would now contain the value of 2001. 32/56 VBA Functions Lookup / Reference Functions MS Excel: CHOOSE Function (WS, VBA) In Excel, the CHOOSE function returns a value from a list of values based on a given position. The syntax for the CHOOSE function is: CHOOSE( position, value1, [value2, ... value_n] ) position is position number in the list of values to return. It must be a number between 1 and 29. value1, value2, ... value_n is a list of up to 29 values. A value can be any one of the following: a number, a cell reference, a defined name, a formula/function, or a text value. Note: If position is less than 1, the CHOOSE function will return #VALUE!. If position is greater than the number of the number of values in the list, the CHOOSE function will return #VALUE!. If position is a fraction (not an integer value), it will be converted to an integer by dropping the fractional component of the number. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to see how you would use the CHOOSE function in a worksheet: Based on the Excel spreadsheet above, the CHOOSE function would return the following: =CHOOSE(1, A1, A2, A3, A4) would return "Tech" =CHOOSE(1, "Tech", "on", "the", "Net") would return "Tech" =CHOOSE(2, A1, A2, A3, A4) would return "on" =CHOOSE(3, A1, A2, A3, A4) would return "the" =CHOOSE(4, A1, A2, A3, A4) would return "Net" =CHOOSE(5, A1, A2, A3, A4) would return #VALUE! =CHOOSE(3.2, A1, A2, A3, A4) would return "the" 33/56 VBA Functions =CHOOSE(3.75, A1, A2, A3, A4) would return "the" VBA Function Example: The CHOOSE function can also be used in VBA code. For example: Dim LValue As String LValue = Choose(1, "Tech", "on", "the", "Net") In this example, the variable called LValue would contain "Tech" as a value. MS Excel: SWITCH Function (VBA) In Excel, the SWITCH function evaluates a list of expressions and returns the corresponding value for the first expression in the list that is TRUE. The syntax for the SWITCH function is: Switch ( expression1, value1, expression2, value2, ... expression_n, value_n ) expression1, expression2, expression_n is a list of expressions that are evaluated. The SWITCH function is looking for the first expression that evaluates to TRUE. value1, value2, ... value_n is a list of values. The SWITCH function will return the value associated with the first expression that evaluates to TRUE. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The SWITCH function can only be used in VBA code. Here are some examples of what the SWITCH function would return: Switch (SupplierID=1, "IBM", SupplierID=2, "HP", SupplierID=3, "NVIDIA") In this example, if SupplierID is 1, then the SWITCH function will return "IBM". If SupplierID is 2, then the SWITCH function will return "HP". If SupplierID is 3, then the SWITCH function will return "NVIDIA". For example: Dim LValue As String LValue = Switch (SupplierID=1, "IBM", SupplierID=2, "HP", SupplierID=3, "NVIDIA") 34/56 VBA Functions Data Type Conversion Functions: MS Excel: CBool Function (VBA) In Excel, the CBOOL function converts a value to a boolean. The syntax for the CBOOL function is: CBool( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CBOOL function can only be used in VBA code. For example: Dim LCompare as Boolean LCompare = CBool(1=2) In this example CBool(1=2) would return false. The variable LCompare would now contain the value false. MS Excel: CBYTE Function (VBA) In Excel, the CBYTE function converts a value to a byte (ie: number between 0 and 255). The syntax for the CBYTE function is: CByte( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CBYTE function can only be used in VBA code. For example: Dim LCompare as Byte LCompare = CByte(12) In this example, the variable LCompare would now contain the byte value 12. MS Excel: CCUR Function (VBA) In Excel, the CCUR function converts a value to currency. The syntax for the CCUR function is: CCur( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CCUR function can only be used in VBA code. For example: Dim LValue As Double Dim LCurValue As Currency LValue = 123.4567812 LCurValue = CCur(LValue) In this example, the CCUR function would return the value 123.4568. The variable called LCurValue would now contain 123.4568. MS Excel: CDATE Function (VBA) In Excel, the CDATE function converts a value to a date. The syntax for the CDATE function is: CDate( expression ) expression must be a valid date. 35/56 VBA Functions Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CDATE function can only be used in VBA code. For example: Dim LstrDate As String Dim LDate As Date LstrDate = "Apr 6, 2003" LDate = CDate(LstrDate) In this example, the variable LDate would now contain the value 4/6/2003. MS Excel: CDBL Function (VBA) In Excel, the CDBL function converts a value to a double. The syntax for the CDBL function is: CDbl( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CDBL function can only be used in VBA code. For example: Dim LDouble As Double LDouble = CDbl(8.45 * 0.005 * 0.01) The variable called LDouble would now contain the value of 0.0004225. MS Excel: CDEC Function (VBA) In Excel, the CDEC function converts a value to a decimal number. The syntax for the CDEC function is: CDec( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CDEC function can only be used in VBA code. For example: Dim LDecimal As Double LDecimal = CDec(8.45 * 0.005 * 0.01) The variable called LDecimal would now contain the value of 0.0004225. MS Excel: CINT Function (VBA) In Excel, the CINT function converts a value to an integer. The syntax for the CINT function is: CInt( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CINT function can only be used in VBA code. For example: Dim LValue As Integer 36/56 VBA Functions LValue = CInt(8.45) In this example, the variable called LValue would now contain the value of 8. Be careful using CINT. If you were to use the following code: Dim LValue As Integer LValue = CInt(8.5) The variable LValue would still contain the value of 8. Until the fraction is greater than .5, the CINT function will not round the number up. If the fraction is less than or equal to .5, the result will round down. If the fraction is greater than .5, the result will round up. We've found it useful in the past to add 0.0001 to the value before applying the CINT function to simulate the regular rounding process. For example, CInt(8.50001) will result in a value of 9. MS Excel: CLNG Function (VBA) In Excel, the CLNG function converts a value to a long integer. The syntax for the CLNG function is: CLng(expression) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CLNG function can only be used in VBA code. For example: Dim LValue As Long LValue = CLng(35150.45) In this example, the variable called LValue would now contain the value of 35150. Be careful using CLNG. If you were to use the following code: Dim LValue As Long LValue = CLng(35150.5) The variable LValue would still contain the value of 35150. Until the fraction is greater than .5, the CLNG function will not round the number up. If the fraction is less than or equal to .5, the result will round down. If the fraction is greater than .5, the result will round up. We've found it useful in the past to add 0.0001 to the value before applying the CLNG function to simulate the regular rounding process. For example, CLng(35150.50001) will result in a value of 35151. MS Excel: CSNG Function (VBA) In Excel, the CSNG function converts a value to a single-precision number. The syntax for the CSNG function is: CSng( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CSNG function can only be used in VBA code. For example: Dim LValue As Single LValue = CSng(8.534535408) In this example, the LValue variable would now contain the value 8.534535408. MS Excel: CSTR Function (VBA) In Excel, the CSTR function converts a value to a string. 37/56 VBA Functions The syntax for the CSTR function is: CStr( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CSTR function can only be used in VBA code. For example: Dim LValue As String LValue = CStr(8) The LValue variable would now contain the string value of "8". MS Excel: CVAR Function (VBA) In Excel, the CVAR function converts a value to a variant. The syntax for the CVAR function is: CVar( expression ) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CVAR function can only be used in VBA code. For example: Dim LValue As Variant LValue = CVar(8) The variable called LValue would now contain the variant value of "8". 38/56 VBA Functions File/Directory Functions MS Excel: CHDIR Statement (VBA) In Excel, the CHDIR statement allows you to change the current directory or folder. The syntax for the CHDIR function is: ChDir path path is the path that you'd like to set the current directory to. Note: The CHDIR lets you change the current directory on the current drive. If you need to change drives, try using the CHDRIVE statement first. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CHDIR statement can be used in VBA code. Here are some examples of what the CHDIR function would return: ChDir "C:\instructions" would set the current directory to C:\instructions ChDir "C:\Documents\Supplies" would set the current directory to C:\Documents\Supplies For example: ChDir "C:\instructions" In this example, the current directory would now be changed to C:\instructions. MS Excel: CHDRIVE Statement (VBA) In Excel, the CHDRIVE statement allows you to change the current drive. The syntax for the CHDRIVE function is: ChDrive drive drive is the drive that you wish to change to. Note: The CHDRIVE lets you change the drive. If you need to change the current directory as well, try using the CHDIR statement. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The CHDRIVE statement can be used in VBA code. Here are some examples of what the CHDRIVE function would return: ChDrive "S" would set the current drive to S ChDrive "C" would set the current drive to C For example: ChDrive "S" ChDir "S:\Games" In this example, the current drive is set to the S drive. Then the current directory is set to S:\Games. MS Excel: CURDIR Function (VBA) In Excel, the CURDIR function returns the current path. The syntax for the CURDIR function is: CurDir( drive ) drive is an optional parameter. If this parameter is omitted, the CURDIR function assumes the current drive. 39/56 VBA Functions Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) Worksheet Function Example: would return "C:\Documents and Settings\user\My Documents" CurDir () CurDir ("G") would return "G:\" VBA Function Example: The CURDIR function can only be used in VBA code. For example: Dim LResult As String LResult = CurDir () In this example, the variable called LResult would now contain the value "C:\Documents and Settings\user\My Documents". MS Excel: DIR Function (VBA) In Excel, the DIR function returns the first filename that matches the pathname and attributes specified. To retrieve additional filenames that matchpathname and attributes, call DIR again with no arguments. The syntax for the DIR function is: Dir [( path [, attributes ] ) ] path is optional. It the path to a file, folder, or directory. If the path is not found, the DIR function will return a zero-length string. attributes is optional. It is the sum of the file attributes. File attributes can be one or a combination of the following values: VB Constant Value Explanation vbNormal 0 Normal (Default) vbReadOnly 1 Read-only vbHidden 2 Hidden vbSystem 4 System file vbVolume 8 Volume label vbDirectory 16 Directory or folder vbAlias 64 File name is an alias Note: You can use wildcard characters to specify multiple files. The patterns that you can choose from are: * allows you to match any string of any length (including zero length) ? allows you to match on a single character If you wish to iterate over all files in a directory, use an empty string: Dir ("") Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The DIR function can only be used in VBA code. Here are some examples of what the DIR function would return: Dir("C:\instructions.doc") would return "instructions.doc" Dir("C:\in*.doc") would return "instructions.doc" 40/56 VBA Functions Dir("C:\instruction?.doc") would return "instructions.doc" For example: Dim LResult As String LResult = Dir("C:\instructions.doc") In this example, the variable called LResult would now contain the filename of the instructions.doc file. Frequently Asked Questions Question: How can I use the DIR function to test whether a file exists? Answer: This can be done with a formula that utilizes a combination of the DIR function, IF function, and LEN function. For example: If Len(Dir("c:\Instructions.doc")) = 0 Then Msgbox "This file does NOT exist." Else Msgbox "This file does exist." End If Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this? Answer: You can test to see if a directory exists using the VBA code below: If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then MkDir "c:\TOTN\Excel\Examples" End If In this example, the code would first check to see if the c:\TOTN\Excel\Examples directory exists. If it doesn't exist, the MKDIR statement would create a new directory called Examples under the c:\TOTN\Excel directory. MS Excel: FILEDATETIME Function (VBA) In Excel, the FILEDATETIME function returns the date and time of when a file was created or last modified. The syntax for the FILEDATETIME function is: FileDateTime ( file_path ) file_path is the path to a file name that you wish to retrieve the created or last modified date for. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The FILEDATETIME function can be used in VBA code. Here are some examples of what the FILEDATETIME function would return: FileDateTime("C:\instructions.doc") would return 6/1/2004 7:40:18 PM FileDateTime("H:\Documents\Supplies.xls") would return 7/3/2004 3:12:14 PM For example: Dim LResult As Date LResult = FileDateTime("C:\instructions.doc") In this example, the variable called LResult would now contain the create or last modified date for the instructions.doc file. MS Excel: FILELEN Function (VBA) In Excel, the FILELEN function returns the size of a file in bytes. The syntax for the FILELEN function is: FileLen( file_path ) file_path is the path to a file name that you wish to retrieve the size for. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 41/56 VBA Functions Type of Function: VBA function (VBA) VBA Function Example: The FILELEN function can only be used in VBA code. Here are some examples of what the FILELEN function would return: would return 55808 FileLen("C:\instructions.doc") FileLen("H:\Documents\Supplies.xls") would return 1254 For example: Dim LResult As Long LResult = FileLen("C:\instructions.doc") In this example, the variable called LResult would now contain the size of the instructions.doc file in bytes. MS Excel: GETATTR Function (VBA) In Excel, the GETATTR function returns an integer that represents the attributes of a file, folder, or directory. The syntax for the GETATTR function is: GetAttr ( path ) path is the path to a file, folder, or directory that you wish to retrieve the attributes for. The GETATTR will return one or a combination of the following values: VB Constant Value Explanation vbNormal 0 Normal vbReadOnly 1 Read-only vbHidden 2 Hidden vbSystem 4 System file vbDirectory 16 Directory or folder vbArchive 32 File has been changed since last backup vbAlias 64 File name is an alias Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The GETATTR function can only be used in VBA code. Here are some examples of what the GETATTR function would return: GetAttr("C:\instructions.doc") would return 0 GetAttr("H:\Documents\Supplies.xls") would return 1 For example: Dim LResult As Integer LResult = GetAttr("C:\instructions.doc") In this example, the variable called LResult would now contain the integer representation of the attributes of the instructions.doc file. MS Excel: MKDIR Function (VBA) In Excel, the MKDIR statement allows you to create a new folder or directory. The syntax for the MKDIR function is: MkDir path path is the folder or directory to create. 42/56 VBA Functions Note: If path is a complex directory structure, the high-level directories must already exist or the MKDIR statement will raise an error. For example, if you executed the following code: MkDir "c:\Test\Excel" The c:\Test directory must already exist. The MKDIR statement will only attempt to create the Excel directory under the c:\Test directory. It will not create the c:\Test directory itself. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The MKDIR function can only be used in VBA code. Here are some examples of what the MKDIR function would return: MkDir "c:\TOTN\Examples" In this example, the MKDIR statement would create a new directory called Examples under the c:\TOTN directory. For example: MkDir "c:\TOTN\Examples\Files" In this example, the directory called Files would be created under the c:\TOTN\Examples directory. Frequently Asked Questions Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this? Answer: You can test to see if a directory exists using the VBA code below: If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then MkDir "c:\TOTN\Excel\Examples" End If In this example, the code would first check to see if the c:\TOTN\Excel\Examples directory exists. If it doesn't exist, the MKDIR statement would create a new directory called Examples under the c:\TOTN\Excel directory. MS Excel: SETATTR Function (VBA) In Excel, the SETATTR statement allows you to set the attributes of a file. The syntax for the SETATTR function is: SetAttr path, attributes path is the path to a file that you wish to set the attributes for. attributes are the attributes that you'd like to attribute to the file. Attributes can be the following values: VB Constant Value Explanation vbNormal 0 Normal (default) vbReadOnly 1 Read-only vbHidden 2 Hidden vbSystem 4 System file vbArchive 32 File has been changed since last backup vbAlias 64 File name is an alias (Macintosh only) Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: VBA function (VBA) VBA Function Example: The SETATTR function can only be used in VBA code. Here are some examples of what the SETATTR function would return: 43/56 VBA Functions SetAttr "C:\instructions.doc", vbNormal would set the file to Normal SetAttr "C:\instructions.doc", vbReadOnly + vbHidden would set the file to ReadOnly and Hidden For example: SetAttr "c:\Test\Doc1.doc", vbReadOnly + vbHidden In this example, the file called Doc1.doc (found in the c:\Test\ directory) would now be set to a ReadOnly, Hidden file. 44/56 VBA Functions Financial Functions MS Excel: DDB Function (WS, VBA) In Excel, the DDB function returns the depreciation of an asset for a given time period based on the doubledeclining balance method. The syntax for the DDB function is: DDB( cost, salvage, life, period, [factor] ) cost is the original cost of the asset. salvage is the salvage value after the asset has been fully depreciated. life is the useful life of the asset or the number of periods that you will be depreciating the asset. period is the period that you wish to calculate the depreciation for. Use the same units as for the life. factor is optional. It is the rate at which the balance declines. If this parameter is omitted, the DDB function will assume the factor to be 2. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the DDB function in a worksheet: This first example returns the depreciation for an asset that costs $10,000, with a salvage value of $5,000. The useful life of the asset is 5 years. The depreciation is being calculated for the first year. =DDB(10000, 5000, 5, 1) This next example returns the depreciation for an asset that costs $10,000, with a salvage value of $5,000. The useful life of the asset is 5 years. The depreciation is being calculated for the second year. =DDB(10000, 5000, 5, 2) This next example returns the depreciation for an asset that costs $10,000, with a salvage value of $5,000. The useful life of the asset is 5 years. The depreciation is being calculated for the third year. =DDB(10000, 5000, 5, 3) VBA Function Example: The DDB function can also be used in VBA code. For example: Dim LValue As Double LValue = DDb(10000, 5000, 5, 2) In this example, the variable called LValue would now contain the value of 1000. MS Excel: FV Function (WS, VBA) In Excel, the FV function returns the future value of an investment based on an interest rate and a constant payment schedule. The syntax for the FV function is: FV( interest_rate, number_payments, payment, [PV], [Type] ) interest_rate is the interest rate for the investment. number_payments is the number of payments for the annuity. payment is the amount of the payment made each period. PV is optional. It is the present value of the payments. If this parameter is omitted, the FV function assumes PV to be 0. Type is optional. It indicates when the payments are due. Type can be one of the following values: Value Explanation 0 Payments are due at the end of the period. (default) 1 Payments are due at the beginning of the period. If the Type parameter is omitted, the FV function assumes a Type value of 0. 45/56 VBA Functions Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the FV function in a worksheet: This first example returns the future value of an investment where you deposit $5,000 into a savings account that earns 7.5% annually. You are going to deposit $250 at the beginning of the month, each month, for 2 years. =FV(7.5%/12, 2*12, -250, -5000, 1) This next example returns the future value of an investment where you deposit $8,000 into a savings account that earns 6% annually. You are going to deposit $50 at the end of the week, each week, for 4 years. =FV(6%/52, 4*52, -50, -8000, 0) This next example returns the future value of an investment where you deposit $6,500 into a savings account that earns 5.25% annually. You are going to deposit $100 at the end of the year, each year, for 10 years. =FV(5.25%/1, 10*1, -100, -6500, 0) VBA Function Example: The FV function can also be used in VBA code. For example: Dim LValue As Currency LValue = FV(0.0525/1, 10*1, -100, -6500, 0) In this example, the variable called LValue would now contain the value of $12,115.19 MS Excel: IPMT Function (WS, VBA) In Excel, the IPMT function returns the interest payment for an investment based on an interest rate and a constant payment schedule. The syntax for the IPMT function is: IPMT( interest_rate, period, number_payments, PV, [FV], [Type] ) interest_rate is the interest rate for the investment. period is the period to calculate the interest rate. It must be a value between 1 and number_payments. number_payments is the number of payments for the annuity. PV is the present value of the payments. FV is optional. It is the future value that you'd like the investment to be after all payments have been made. If this parameter is omitted, the IPMTfunction will assume a FV of 0. Type is optional. It indicates when the payments are due. Type can be one of the following values: Value Explanation 0 Payments are due at the end of the period. (default) 1 Payments are due at the beginning of the period. If the Type parameter is omitted, the IPMT function assumes a Type value of 0. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the IPMT function in a worksheet: This first example returns the interest payment for a $5,000 investment that earns 7.5% annually for 2 years. The interest payment is calculated for the 8th month and payments are due at the end of each month. =IPMT(7.5%/12, 8, 2*12, 5000) 46/56 VBA Functions This next example returns the interest payment for a $8,000 investment that earns 6% annually for 4 years. The interest payment is calculated for the 30th week and payments are due at the beginning of each week. =IPMT(6%/52, 30, 4*52, 8000, 0 ,1) This next example returns the interest payment for a $6,500 investment that earns 5.25% annually for 10 years. The interest payment is calculated for the 4th year and payments are due at the end of each year. =IPMT(5.25%/1, 4, 10*1, 6500) VBA Function Example: The IPMT function can also be used in VBA code. For example: Dim LNumber As Currency LNumber = IPmt(0.0525/1, 4, 10*1, 6500) In this example, the variable called LNumber would now contain the value of -256.504747. MS Excel: IRR Function (WS, VBA) In Excel, the IRR function returns the internal rate of return for a series of cash flows. The cash flows must occur at regular intervals, but do not have to be the same amounts for each interval. The syntax for the IRR function is: IRR( range, [estimated_irr] ) range is a range of cells that represent the series of cash flows. estimated_irr is optional. It is the your guess at the internal rate of return. If this parameter is omitted, the IRR function assumes an estimated_irr of 0.1 or 10%. Note: Excel tries to recalculate the IRR until the result is accurate within 0.00001 percent. If after 20 tries Excel has not calculated an accurate value, it will return the #NUM! error. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to see how you would use the IRR function in a worksheet: Based on the Excel spreadsheet above: 47/56 VBA Functions This first example returns an internal rate of return of 28%. It assumes that you start a business at a cost of $7,500. You net the following income for the first four years: $3,000, $5,000, $1,200, and $4,000. =IRR(A1:A5) This next example returns an internal rate of return of 5%. It assumes that you start a business at a cost of $10,000. You net the following income for the first three years: $3,400, $6,500, and $1,000. =IRR(B1:B4) VBA Function Example: The IRR function can also be used in VBA code. For example: Dim LNumber As Double Static Values(5) As Double Values(0) = -7500 Values(1) = 3000 Values(2) = 5000 Values(3) = 1200 Values(4) = 4000 LNumber = Irr(Values()) In this example, the variable called LNumber would now contain the value of 0.276668413. MS Excel: MIRR Function (WS, VBA) In Excel, the MIRR function returns the modified internal rate of return for a series of cash flows. The internal rate of return is calculated by using both the cost of the investment and the interest received by reinvesting the cash. The cash flows must occur at regular intervals, but do not have to be the same amounts for each interval. The syntax for the MIRR function is: MIRR( range, finance_rate, reinvestment_rate ) range is a range of cells that represent the series of cash flows. finance_rate is the interest rate that you pay on the cash flow amounts. reinvestment_rate is the interest rate that you receive on the cash flow amounts as they are reinvested. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to see how you would use the MIRR function in a worksheet: 48/56 VBA Functions Based on the Excel spreadsheet above: This first example returns a modified internal rate of return of 19%. It assumes that you start a business at a cost of $7,500 - this amount was borrowed at a rate of 5%. You net the following income for the first four years: $3,000, $5,000, $1,200, and $4,000. The net income was reinvested at a rate of 8%. =MIRR(A1:A5, 5%, 8%) This next example returns a modified internal rate of return of 7%. It assumes that you start a business at a cost of $10,000 - this amount was borrowed at a rate of 6.5%. You net the following income for the first three years: $3,400, $6,500, and $1,000. The net income was reinvested at a rate of 10%. =MIRR(B1:B4, 6.5%, 10%) VBA Function Example: The MIRR function can also be used in VBA code. For example: Dim LNumber As Double Static Values(5) As Double Values(0) = -7500 Values(1) = 3000 Values(2) = 5000 Values(3) = 1200 Values(4) = 4000 LNumber = Mirr(Values(), 0.05, 0.08) In this example, the variable called LNumber would now contain the value of 0.16506818. MS Excel: NPER Function (WS, VBA) In Excel, the NPER function returns the number of periods for an investment based on an interest rate and a constant payment schedule. The syntax for the NPER function is: NPER( interest_rate, payment, PV, [FV], [Type] ) interest_rate is the interest rate for the investment. payment is the amount of the payment for each period. This should be entered as a negative value. PV is the present value of the payments. FV is optional. It is the future value that you'd like the investment to be after all payments have been made. If this parameter is omitted, the NPER function will assume a FV of 0. Type is optional. It indicates when the payments are due. Type can be one of the following values: 49/56 VBA Functions Value Explanation 0 Payments are due at the end of the period. (default) 1 Payments are due at the beginning of the period. If the Type parameter is omitted, the NPER function assumes a Type value of 0. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the NPER function in a worksheet: This first example returns the number of monthly payments (monthly payments are $150) for a $5,000 investment that earns 7.5% annually. Payments are due at the end of the period. =NPER(7.5%/12, -150, 5000) This next example returns the number of weekly payments (weekly payments are $175) for a $8,000 investment that earns 6% annually. Payments are due at the beginning of each week. =NPER(6%/52, -175, 8000, 0 ,1) This next example returns the number of annual payments (annual payments are $200) for a $1,500 investment that earns 5.25% annually. Payments are due at the end of each year. =NPER(5.25%/1, -200, 1500) VBA Function Example: The NPER function can also be used in VBA code. For example: Dim LValue As Double LValue = NPer(0.0525/1, -200, 1500) In this example, the variable called LValue would now contain the value of 9.780722988. MS Excel: NPV Function (WS, VBA) In Excel, the NPV function returns the net present value of an investment. The syntax for the NPV function is: NPV( discount_rate, value1, [value2, ... value_n] ) discount_rate is the discount rate for the period. value1, value2, ... value_n are the future payments and income for the investment (ie: cash flows). There can be up to 29 values entered. Note: Microsoft Excel's NPV function does not account for the intial cash outlay, or may account for it improperly depending on the version of Excel. However, there is a workaround. This workaround requires that you NOT include the initial investment in the future payments/income for the investment (ie: value1, value2, ... value_n), but instead, you need to subtract from the result of the NPV function, the amount of the initial investment. The workaround formula is also different depending on whether the cash flows occur at the end of the period (EOP) or at the beginning of the period (BOP). If the cash flows occur at the end of the period (EOP), you would use the following formula: =NPV( discount_rate, value1, value2, ... value_n ) - Initial Investment If the cash flows occur at the beginning of the period (BOP), you would use the following formula: =NPV( discount_rate, value2, ... value_n ) - Initial Investment + value1 Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) 50/56 VBA Functions Worksheet Function Example: Let's take a look at an example to how you would use the NPV function in a worksheet: This first example returns a net present value of $3,457.19. It assumes that you pay $7,500 as an initial investment . You then receive the following income for the first four years (EOP): $3,000, $5,000, $1,200, and $4,000. An annual discount rate of 8% is used. =NPV(8%, 3000, 5000, 1200, 4000) - 7500 This next example returns a net present value of $8,660.77. It assumes that you pay $10,000 as an initial investment. You then receive the following income for the first three years (BOP): $3,400, $6,500, and $10,000. An annual discount rate of 5% is used. =NPV(5%, 6500, 10000) - 10000 + 3400 VBA Function Example: The NPV function can also be used in VBA code as demonstrated by the following example: This example returns a net present value of $3,457.19. It assumes that you pay $7,500 as an initial investment . You then receive the following income for the first four years (EOP): $3,000, $5,000, $1,200, and $4,000. An annual discount rate of 8% is used. The VBA code would be: Dim LNumber As Double Static Values(4) As Double Values(0) = 3000 Values(1) = 5000 Values(2) = 1200 Values(3) = 4000 LNumber = Npv(0.08, Values()) - 7500 In this example, the variable called LNumber would now contain the value of $3,457.19. MS Excel: PMT Function (WS, VBA) In Excel, the PMT function returns the payment amount for a loan based on an interest rate and a constant payment schedule. The syntax for the PMT function is: PMT( interest_rate, number_payments, PV, [FV], [Type] ) interest_rate is the interest rate for the loan. number_payments is the number of payments for the loan. PV is the present value or principal of the loan. FV is optional. It is the future value or the loan amount outstanding after all payments have been made. If this parameter is omitted, the PMT function assumes a FV value of 0. Type is optional. It indicates when the payments are due. Type can be one of the following values: Value Explanation 0 Payments are due at the end of the period. (default) 1 Payments are due at the beginning of the period. If the Type parameter is omitted, the PMT function assumes a Type value of 0. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the PMT function in a worksheet: This first example returns the monthly payment on a $5,000 loan at an annual rate of 7.5%. The loan is paid off in 2 years (ie: 2 x 12). All payments are made at the beginning of the period. =PMT(7.5%/12, 2*12, 5000, 0, 1) 51/56 VBA Functions This next example returns the weekly payment on a $8,000 loan at an annual rate of 6%. The loan is paid off in 4 years (ie: 4 x 52). All payments are made at the end of the period. =PMT(6%/52, 4*52, 8000, 0, 0) This next example returns the annual payment on a $6,500 loan at an annual rate of 5.25%. The loan is paid off in 10 years (ie: 10 x 1). All payments are made at the end of the period. =PMT(5.25%/1, 10*1, 6500, 0, 0) This final example returns the monthly payment on a $5,000 loan at an annual rate of 8%. The loan is paid on for 3 years (ie: 3 x 12) with a remaining balance on the loan of $1,000 after the 3 years. All payments are made at the end of the period. =PMT(8%/12, 3*12, 5000, -1000, 0) VBA Function Example: The PMT function can also be used in VBA code. For example: Dim LValue As Currency LValue = Pmt(0.08/12, 3*12, 5000, -1000, 0) In this example, the variable called LValue would now contain the value of ($132.01) MS Excel: PPMT Function (WS, VBA) In Excel, the PPMT function returns the payment on the principal for a particular payment based on an interest rate and a constant payment schedule. The syntax for the PPMT function is: PPMT( interest_rate, period, number_payments, PV, [FV], [Type] ) interest_rate is the interest rate for the loan. period is the period used to determine how much principal has been repaid. Period must be a value between 1 and number_payments. number_payments is the number of payments for the loan. PV is the present value or principal of the loan. FV is optional. It is the future value or the loan amount outstanding after all payments have been made. If this parameter is omitted, the PPMTfunction assumes a FV value of 0. Type is optional. It indicates when the payments are due. Type can be one of the following values: Value Explanation 0 Payments are due at the end of the period. (default) 1 Payments are due at the beginning of the period. If the Type parameter is omitted, the PPMT function assumes a Type value of 0. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the PPMT function in a worksheet: This first example returns the amount of principal paid off by the payment made in the 5th month of a $5,000 loan with monthly payments at an annual interest rate of 7.5%. The loan is to be paid off in 2 years (ie: 2 x 12). All payments are made at the beginning of the period. =PPMT(7.5%/12, 5, 2*12, 5000, 0, 1) This next example returns the amount of principal paid off by the payment made in the 20th week of a $8,000 loan with weekly payments at an annual interest rate of 6%. The loan is to be paid off in 4 years (ie: 4 x 52). All payments are made at the end of the period. =PPMT(6%/52, 20, 4*52, 8000, 0, 0) 52/56 VBA Functions This next example returns the amount of principal paid off by the payment made in the 4th year of a $6,500 loan with annual payments at an annual interest rate of 5.25%. The loan is to be paid off in 10 years (ie: 10 x 1). All payments are made at the end of the period. =PPMT(5.25%/1, 4, 10*1, 6500, 0, 0) This final example returns the amount of principal paid off by the payment made in the 14th month of a $5,000 loan with annual payments at an annual interest rate of 8%. The loan is to be paid off in 3 years (ie: 3 x 12) with a remaining balance on the loan of $1,000 after the 3 years. All payments are made at the end of the period. =PPMT(8%/12, 14, 3*12, 5000, 1000, 0) VBA Function Example: The PPMT function can also be used in VBA code. For example: Dim LValue As Currency LValue = PPmt(0.08/12, 14, 3*12, 5000, 1000, 0) In this example, the variable called LValue would now contain the value of ($161.37). MS Excel: PV Function (WS, VBA) In Excel, the PV function returns the present value of an investment based on an interest rate and a constant payment schedule. The syntax for the PV function is: PV( interest_rate, number_payments, payment, [FV], [Type] ) interest_rate is the interest rate for the investment. number_payments is the number of payments for the annuity. payment is the amount of the payment made each period. If this parameter is omitted, you must enter a FV value. FV is optional. It is the future value of the payments. If this parameter is omitted, the PV function assumes FV to be 0. Type is optional. It indicates when the payments are due. Type can be one of the following values: Value Explanation 0 Payments are due at the end of the period. (default) 1 Payments are due at the beginning of the period. If the Type parameter is omitted, the PV function assumes a Type value of 0. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the PV function in a worksheet: This first example returns the present value of an investment that pays $250 at the end of every month for 2 years. The money paid out will earn 7.5% annually. =PV(7.5%/12, 2*12, 250, , 0) This next example returns the present value of an investment that pays $50 at the beginning of every week for 4 years. The money paid out will earn 6% annually. =PV(6%/52, 4*52, 50, , 1) This next example returns the present value of an investment that pays $100 at the end of every year for 10 years. The money paid out will earn 5.25% annually. =PV(5.25%/1, 10*1, 100, , 0) VBA Function Example: The PV function can also be used in VBA code. For example: 53/56 VBA Functions Dim LValue As Currency LValue = PV(0.0525/1, 10*1, 100, , 0) In this example, the variable called LValue would now contain the value of ($762.88) MS Excel: RATE Function (WS, VBA) In Excel, the RATE function returns the interest rate for an annuity. The syntax for the RATE function is: RATE( number_payments, payment, PV, [FV], [Type], [Estimate] ) number_payments is the number of payments for the annuity. payment is the amount of the payment made each period. PV is the present value. FV is optional. It is the future value. If this parameter is omitted, the RATE function assumes a FV value of 0. Type is optional. It indicates when the payments are due. Type can be one of the following values: Value Explanation 0 Payments are due at the end of the period. (default) 1 Payments are due at the beginning of the period. If the Type parameter is omitted, the RATE function assumes a Type value of 0. Estimate is optional. It is your guess at what the rate will be. If this parameter is omitted, the RATE function assumes an Estimate of 10%. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the RATE function in a worksheet: This first example returns the interest rate on a $5,000 loan where monthly payments of $250 are made for 2 years. All payments are made at the end of the period. =RATE(2*12, -250, 5000) This next example returns the interest rate on a $5,000 loan where monthly payments of $250 are made for 2 years. All payments are made at the beginning of the period. =RATE(2*12, -250, 5000, , 1) This next example returns the interest rate on a $8,000 loan where weekly payments of $700 are made for 4 years. All payments are made at the end of the period. =RATE(4*52, -700, 8000, , 0) This final example returns the interest rate on a $6,500 loan where annual payments of $1,000 are made for 10 years. All payments are made at the end of the period. =RATE(10*1, -1000, 6500) VBA Function Example: The RATE function can also be used in VBA code. For example: Dim LValue As Double LValue = Rate(10*1, -1000, 6500) In this example, the variable called LValue would now contain the value of 0.087113756. MS Excel: SLN Function (WS, VBA) In Excel, the SLN function returns the depreciation of an asset for a period based on the straight-line depreciation method. The syntax for the SLN function is: SLN( cost, salvage, life ) 54/56 VBA Functions cost is the original cost of the asset. salvage is the salvage value after the asset has been fully depreciated. life is the useful life of the asset or the number of periods that you will be depreciating the asset. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the SLN function in a worksheet: This first example returns the depreciation for an asset that costs $10,000, with a salvage value of $5,000. The useful life of the asset is 5 years. =SLN(10000, 5000, 5) This next example returns the depreciation for an asset that costs $8,000, with a salvage value of $0. The useful life of the asset is 7 years. =SLN(8000, 0, 7) VBA Function Example: The SLN function can also be used in VBA code. For example: Dim LValue As Double LValue = SLN(8000, 0, 7) In this example, the variable called LValue would now contain the value of 1142.857143. MS Excel: SYD Function (WS, VBA) In Excel, the SYD function returns the depreciation of an asset for a given time period based on the sum-ofyears' digits depreciation method. The syntax for the SYD function is: SYD( cost, salvage, life, period ) cost is the original cost of the asset. salvage is the salvage value after the asset has been fully depreciated. life is the useful life of the asset or the number of periods that you will be depreciating the asset. period is the period that you wish to calculate the depreciation for. Use the same units as for the life. Applies To: Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000 Type of Function: Worksheet function (WS) VBA function (VBA) Worksheet Function Example: Let's take a look at an example to how you would use the SYD function in a worksheet: This first example returns the depreciation for an asset that costs $10,000, with a salvage value of $5,000. The useful life of the asset is 5 years. The depreciation is being calculated for the first year. =SYD(10000, 5000, 5, 1) This next example returns the depreciation for an asset that costs $10,000, with a salvage value of $5,000. The useful life of the asset is 5 years. The depreciation is being calculated for the second year. =SYD(10000, 5000, 5, 2) This next example returns the depreciation for an asset that costs $8,000, with a salvage value of $0. The useful life of the asset is 7 years. The depreciation is being calculated for the third year. =SYD(8000, 0, 7, 3) VBA Function Example: The SYD function can also be used in VBA code. For example: Dim LValue As Double 55/56 VBA Functions LValue = Syd(8000, 0, 7, 3) In this example, the variable called LValue would now contain the value of 1428.571429. 56/56