Understanding VBA Functions and Their Uses
A function performs a calculation and returns a single value. The SUM function adds the sum of a range of values. The same holds true for functions used in your VBA expressions: Each function does its thing and returns a single value.
The functions you use in VBA can come from three sources:
- Built-in functions provided by VBA
- Worksheet functions provided by Excel
- Custom functions that you (or someone else) write, using VBA
VBA provides numerous built-in functions. Some of these functions take arguments and some do not.
VBA function examples
Here are a few examples of using VBA functions in code. Note the use of the MsgBox function to display a value in a message box. Yes, MsgBox is a VBA function — a rather unusual one, but a function nonetheless. This useful function displays a message in a pop-up dialog box.
Displaying the system date
The first example uses VBA's Date function to display the current system date in a message box:
Notice that the Date function doesn't use an argument. Unlike worksheet functions, a VBA function with no argument doesn't require an empty set of parentheses. In fact, if you provide an empty set of parentheses, the VBE will remove them.
To get the system date and time, use the Now function instead of the Date function. Or to get only the time, use the Time function.
Finding a string length
The following procedure uses the VBA Len function, which returns the length of a string. The Len function takes one argument: the string. When you execute this procedure, the message box displays 11 because the argument has 11 characters.
Dim MyString As String
Dim StringLength As Integer
MyString = "Hello World"
StringLength = Len(MyString)
Excel also has a function, which you can use in your worksheet formulas. The Excel version and the VBA function work the same.
Displaying the integer part of a number
The following procedure uses the Fix function, which returns the integer portion of a value — the value without any decimal digits:
Dim MyValue As Double
Dim IntValue As Integer
MyValue = 123.456
IntValue = Fix(MyValue)
In this case, the message box displays 123.
VBA has a similar function called Int. The difference between Int and Fix is how each deals with negative numbers.
- Int returns the first negative integer that's less than or equal to the argument.
- Fix returns the first negative integer that's greater than or equal to the argument.
Determining a file size
The following Sub procedure displays the size, in bytes, of the Excel executable file. It finds this value by using the FileLen function.
Dim TheFile As String
TheFile = "c:\MSOFFICE\EXCEL\EXCEL.EXE"
Notice that this routine hard codes the filename (that is, it explicitly states the path). Generally, this isn't a good idea. The file might not be on the C drive, or the Excel folder may have a different name. The following statement shows a better approach:
TheFile = Application.Path & "\EXCEL.EXE"
Path is a property of the Application object. It simply returns the name of the folder in which the application (that is, Excel) is installed (without a trailing backslash).
Identifying the type of a selected object
The following procedure uses the TypeName function, which returns the type of the selected object (as a string):
Dim SelType As String
SelType = TypeName(Selection)
This could be a Range, a ChartObject, a TextBox, or any other type of object that can be selected.
The TypeName function is very versatile. You can also use this function to determine the data type of a variable.
VBA functions that do more than return a value
A few VBA functions go above and beyond the call of duty. Rather than simply return a value, these functions have some useful side effects. Table 1 lists them.
Table 1: Functions with Useful Side Benefits
What It Does
Displays a handy dialog box containing a message and buttons. The function returns a code that identifies which button the user clicks.
Displays a simple dialog box that asks the user for some input. The function returns whatever the user enters into the dialog box.
Executes another program. The function returns the task ID (a unique identifier) of the other program (or an error if the function can't start the other program).
Discovering VBA functions
How do you find out which functions VBA provides? Good question. The best source is the Excel Visual Basic Help system. Table 2 contains a partial list of functions (minus some of the more specialized or obscure functions).
For complete details on a particular function, type the function name into a VBA module, move the cursor anywhere in the text, and press F1.
Table 2: VBA's Most Useful Built-in Functions
What It Does
Returns a number's absolute value
Returns a variant containing an array
Converts the first character of a string to its ASCII value
Returns the arctangent of a number
Returns a value from a list of items
Converts an ANSI value to a string
Returns a number's cosine
Returns the current path
Returns the current system date
Returns a date to which a specified time interval has been
added — for example, one month from a particular date
Returns an integer showing the number of specified time intervals between two dates, for example the number of months between now and your birthday
Returns an integer containing the specified part of a given
date — for example, a date's day of the year
Converts a date to a serial number
Converts a string to a date
Returns the day of the month from a date value
Returns the name of a file or directory that matches a pattern
Returns the line number that caused an error
Returns the error number of an error condition
Returns the error message that corresponds to an error number
Returns the base of the natural logarithm (e) raised to a power
Returns the number of bytes in a file
Returns a number's integer portion
Displays an expression in a particular format
Returns a value from the Windows registry
Converts from decimal to hexadecimal
Returns the hours portion of a time
Displays a box to prompt a user for input
Returns the position of a string within another string
Returns the integer portion of a number
Returns the interest payment for an annuity or loan
Returns True if a variable is an array
Returns True if an expression is a date
Returns True if a variable has not been initialized
Returns True if an expression is an error value
Returns True if an optional argument was not passed to a procedure
Returns True if an expression contains no valid data
Returns True if an expression can be evaluated as a number
Returns True if an expression references an OLE Automation object
Returns the smallest subscript for a dimension of an array
Returns a string converted to lowercase
Returns a specified number of characters from the left of a string
Returns the number of characters in a string
Returns the natural logarithm of a number to base e
Returns a copy of a string, with any leading spaces removed
Returns a specified number of characters from a string
Returns the minutes portion of a time value
Returns the month from a date value
Displays a message box and (optionally) returns a value
Returns the current system date and time
Returns a numeric RGB value representing a color
Returns a specified number of characters from the right of a string
Returns a random number between 0 and 1
Returns a copy of a string, with any trailing spaces removed
Returns the seconds portion of a time value
Returns an integer that indicates a number's sign
Runs an executable program
Returns a number's sine
Returns a string with a specified number of spaces
Returns a number's square root
Returns a string representation of a number
Returns a value indicating the result of a string comparison
Returns a repeating character or string
Returns a number's tangent
Returns the current system time
Returns the number of seconds since midnight
Returns the time for a specified hour, minute, and second
Converts a string to a time serial number
Returns a string without leading or trailing spaces
Returns a string that describes a variable's data type
Returns the largest available subscript for an array's dimension
Converts a string to uppercase
Returns the numbers contained in a string
Returns a value indicating a variable's subtype
Returns a number representing a day of the week
Returns the year from a date value