The VBA (Visual Basic for Applications) language provides users with an extensive set of Built-in Functions. These functions are used for performing numerical calculations, converting data, processing text, handling errors, and many other operations.
In this tutorial from Iran VBA, we will review the complete list of VBA’s built-in functions along with explanations, examples, and results so you can use them effectively in your own projects.
Definition
Built-in or intrinsic functions are those whose implementation and optimisation have been handled by the VBA language compiler and are made available to the programmer.
Built-in functions are embedded within the VBA compiler to increase speed, simplicity, and efficiency, taking on common operations that might be used by most programmers during development. For example, the built-in Sin function is included in the compiler to calculate the sine.
Built-in functions perform operations and return a value, similar to a Function procedure, with the key difference being that the architecture of built-in functions is handled by the compiler. Furthermore, built-in functions in VBA are not categorised as procedures, meaning they will not perform any operation until they are placed within a procedure.
VBA supports a wide range of built-in functions, which we will explore below.
1. Conversion Functions
Conversion functions in VBA are used to change the data type or value into another format. These functions are very useful when working with text inputs or mixed data.
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
Asc |
Asc(string) |
Calculates the ASCII code of the first character in the string argument | Asc("ABC") |
65 |
Chr |
Chr(charcode)ChrB(charcode)ChrW(charcode)
|
Returns the character associated with the character code Returns the byte data associated with the character code Returns the Unicode character associated with the character code |
Chr(65) |
A |
CVErr |
CVErr(errornumber) |
Creates a user-defined error code | CVErr(2001) |
Error 2001 |
Format |
Format(Expression, [Format], [FirstDayOfWeek], [FirstWeekOfYear]) |
Formats an expression | Format("17:4:23", "hh:mm:ss") |
17:04:23 |
Hex |
Hex(number) |
Converts numbers from base 10 to base 16 | Hex(10) |
A |
Oct |
Oct(number) |
Converts numbers from base 10 to base 8 | Oct(459) |
713 |
Str |
Str(number) |
Returns the string representation of a number | Str(459) |
" 459" |
Val |
Val(string) |
Returns the numerical value of the numbers contained in a string | Val(" 2 45 7") |
2457 |
2. Mathematical Functions
VBA’s mathematical functions are used for calculations such as sine, logarithm, absolute value, and generating random numbers. Some of the most commonly used ones are listed below.
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
Abs |
Abs(number) |
Calculates the absolute value of a number | Abs(-50.3) |
50.3 |
Atn |
Atn(number) |
Calculates the arctangent of a number (the result is in radians) | Atn(1)*4 |
3.14159265358979 |
Cos |
Cos(number) |
Calculates the cosine of an angle (the number argument must be in radians) | Cos(0) |
1 |
Exp |
Exp(number) |
Exponential function ex | Exp(1) |
2.71828182845905 |
IntFix |
Int(number)Fix(number) |
Returns the integer portion of a number (The Int function always rounds number down to the nearest integer, whereas the Fix function simply truncates the fractional part of number) |
Int(99.8)Fix(99.8)Int(-99.2)Fix(-99.2)
|
99 99 -100 -99 |
Log |
Log(number) |
Calculates the natural logarithm of the number argument | Log(2.71828182845905) |
1 |
Rnd |
Rnd [(Number)] |
Generates a random number less than 1 and greater than or equal to 0 | Int((6 * Rnd) + 1) |
Generates a random number between one and six |
Sgn |
Sgn(number) |
Returns the sign of the number argument |
Sgn(12)Sgn(-12)Sgn(0)
|
1 -1 0 |
Sin |
Sin(number) |
Calculates the sine of an angle (the number argument must be in radians) | Sin(0) |
0 |
Sqr |
Sqr(number) |
Calculates the square root of a number | Sqr(4) |
2 |
Tan |
Tan(number) |
Calculates the tangent of an angle (the number argument must be in radians) | tan(0.785398) |
0.999999673205157 |
3. Data Type Conversion Functions
In VBA, you sometimes need to change the data type of a variable (e.g., from string to number). The functions in this section are designed for this purpose.
| Function | Syntax | Purpose | Function Result Data Type |
|---|---|---|---|
CBool |
CBool(expression) |
Converts the expression to Boolean data type | Boolean |
CByte |
CByte(expression) |
Converts the expression to Byte data type | Byte |
CCur |
CCur(expression) |
Converts the expression to Currency data type | Currency |
CDate |
CDate(expression) |
Converts the expression to Date data type | Date |
CDbl |
CDbl(expression) |
Converts the expression to Double data type | Double |
CDec |
CDec(expression) |
Converts the expression to Decimal data type | Decimal |
CInt |
CInt(expression) |
Converts the expression to Integer data type | Integer |
CLng |
CLng(expression) |
Converts the expression to Long data type | Long |
CLngLng |
CLngLng(expression) |
Converts the expression to LongLong data type | LongLong (only on 64-bit platforms) |
CLngPtr |
CLngPtr(expression) |
Converts the expression to LongPtr data type | LongPtr |
CSng |
CSng(expression) |
Converts the expression to Single data type | Single |
CStr |
CStr(expression) |
Converts the expression to String data type | String |
CVar |
CVar(expression) |
Converts the expression to Variant data type | Variant |
4. String Functions
String functions in VBA are used for working with text (String). Common operations include trimming, searching, replacing, and calculating string length.
| Function Name | Description | Example | Output |
|---|---|---|---|
Len() |
Returns the length of a string. | Len("Iran VBA") |
8 |
Left() |
Returns a specified number of characters from the left side of a string. | Left("Excel VBA", 5) |
Excel |
Right() |
Returns a specified number of characters from the right side of a string. | Right("Excel VBA", 3) |
VBA |
Mid() |
Extracts a part of a string starting from a specified position. | Mid("IranVBA", 3, 4) |
anVB |
InStr() |
Returns the position of the first occurrence of a substring within the main string. | InStr("Visual Basic", "Basic") |
8 |
Replace() |
Replaces part of the text with new text. | Replace("Hello World", "World", "VBA") |
Hello VBA |
Combined Example:
' Remove extra spaces from text and display the final length
Dim txt As String
txt = " Iran VBA "
MsgBox Len(Trim(txt)) ' Output: 8
5. Date & Time Functions
Date and time functions in VBA are used to retrieve or calculate dates and times, find the difference between two dates, and format time values.
| Function Name | Description | Example | Output |
|---|---|---|---|
Now() |
Returns the current system date and time. | Now() |
02/11/2025 20:10:06 |
Date() |
Returns only the current date. | Date() |
02/11/2025 |
Time() |
Returns only the current time. | Time() |
20:10:52 |
DateAdd() |
Adds a specified time interval to a date. | DateAdd("d", 7, Date()) |
7 days after today09/11/2025 |
DateDiff() |
Calculates the difference between two dates in days, months, or years. | DateDiff("d", #1/1/2024#, Date()) |
Number of days since the start of the year671 |
Format() |
Custom formatting for date or time. | Format(Now(), "yyyy/mm/dd hh:nn") |
2025/11/02 20:11 |
Example:
' Calculate age based on date of birth
Dim age As Integer
age = DateDiff("yyyy", #22/05/1990#, Date)
MsgBox "Your age: " & age
6. File & System Functions
File and system functions in VBA are used to check for the existence of files or folders, access system information, and working paths.
| Function Name | Description | Example | Output |
|---|---|---|---|
Dir() |
Returns the name of a file or folder matching a pattern. | Dir("C:\*.xls*") |
First Excel file on C drive |
FileLen() |
Returns the size of a file in bytes. | FileLen("C:\Report.xlsm") |
e.g., 204800 |
GetAttr() |
Returns the attributes of a file (e.g., read-only or hidden). | GetAttr("C:\Report.xlsm") |
1 = ReadOnly |
CurDir() |
Returns the current working path. | CurDir() |
C:\Users\Admin\Documents |
Environ() |
Accesses system environment variables such as username. | Environ("USERNAME") |
Admin |
Example:
' Check if a file exists
If Dir("C:\Data\Report.xlsx") <> "" Then
MsgBox "File exists."
Else
MsgBox "File not found."
End If
7. Error Handling Functions
The Err object in VBA is used to access information about the last error that occurred. This object is automatically initialised when an error occurs and includes properties such as the error number (Err.Number), error description (Err.Description), and its source (Err.Source). Using Err.Clear clears the current error information, ready to receive the next error.
Sub Example_ErrorHandling()
On Error Resume Next ' Continue execution even if an error occurs
Dim x As Integer
x = 10 / 0 ' Cause an error (division by zero)
If Err.Number <> 0 Then
MsgBox "Error code: " & Err.Number & vbCrLf & _
"Description: " & Err.Description & vbCrLf & _
"Source: " & Err.Source, vbExclamation, "Error Management in VBA"
Err.Clear ' Clear the error for reuse
End If
End Sub
VBA has several built-in functions for detecting and managing runtime errors. These functions are typically used with the On Error statement.
| Function Name | Description | Example | Output |
|---|---|---|---|
Err.Number |
Returns the number of the last error. | Err.Number |
e.g., 11 (Division by zero) |
Err.Description |
Returns the textual description of the error. | Err.Description |
Division by zero |
Err.Clear() |
Clears the current error. | Err.Clear() |
--- |
IsError() |
Checks whether the given value is an error type. | IsError(CVErr(2004)) |
True |
CVErr() |
Creates an error value for use in Excel cells. | CVErr(2004) |
Error 2004 |
Example:
On Error Resume Next
Dim x As Integer
x = 10 / 0
If Err.Number <> 0 Then
MsgBox "Error: " & Err.Description
Err.Clear
End If
8. Other Built-in Functions
This section includes miscellaneous but useful functions that don’t fit into the previous categories, such as Format, Now, and IsNull.
MsgBox Function
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
MsgBox |
MsgBox (prompt, [ buttons, ] [ title, ] [ helpfile, context ]) |
Displays a message box to the user using the arguments (arglist) | MsgBox "Do you confirm the form information?", vbOKCancel |
Displays a message box to the user containing two buttons: OK and Cancel |
- List arguments are separated using a comma (,).
- Except for the mandatory prompt argument, all other arguments are optional.
- The prompt argument can be a String (as in the table example) or a variable containing string data.
- The buttons argument configures the combination of buttons to be used in the message box.
InputBox Function
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
InputBox |
InputBox (prompt, [ title ], [ default ], [ xpos ], [ ypos ], [ helpfile, context ]) |
Displays an input box to the user, receives information from the user in a text box, and after the user clicks, returns a string containing the contents of the text box. | InputBox "Please enter your date of birth" |
|
The return value of the built-in InputBox function is of String data type. Therefore, to store the information received from the user, you must declare a variable of type String.
Array Function
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
Array |
Array(arglist) |
Creates an array using the list of arguments (arglist) | MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") |
MyWeek(2) = Tue |
- List arguments are separated using a comma (,).
- The lower bound of an array is zero by default. You can change the lower bound to one using the
Option Base 1statement. Note that the Option Base statement can only be used at the module level. The example above assumes Option Base is set to 1.
LBound Function
| Function | Syntax | Purpose |
|---|---|---|
LBound |
LBound(arrayname, [dimension]) |
Returns the smallest available subscript for the indicated dimension of an array (arrayname). |
- The dimension argument specifies which dimension’s lower bound is to be returned. Use 1 for the first dimension, 2 for the second, and so on. If omitted, the default is 1.
- The LBound function is used with the UBound function to determine the size of an array dimension. For example,
UBound(A, 2) - LBound(A, 2) + 1
calculates the size of the second dimension of array A. - The Option Base setting can affect the return value of the LBound function.
- Using the To clause when declaring an array with any of the variable declaration statements (Dim, Private, Public, ReDim, Static) will cause the number specified in the declaration to be set as the lower bound. The value specified in the To clause takes precedence over the Option Base setting. (This is illustrated in the example).
Example
Dim Lower
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' Declare a three-dimensional array with specified upper and lower bounds
Dim AnyArray(10) ' Declare a one-dimensional array
Lower = Lbound(MyArray, 1) ' Returns: 1.
Lower = Lbound(MyArray, 2) ' Returns: 5.
Lower = Lbound(MyArray, 3) ' Returns: 10.
Lower = Lbound(AnyArray) ' Returns: 0 or 1. Depends on the Option Base setting.
UBound Function
| Function | Syntax | Purpose |
|---|---|---|
UBound |
UBound(arrayname, [dimension]) |
Returns the largest available subscript for the indicated dimension of an array (arrayname). |
- The dimension argument specifies which dimension’s upper bound is to be returned. Use 1 for the first dimension, 2 for the second, and so on. If omitted, the default is 1.
- The UBound function is used with the LBound function to determine the size of an array dimension. For example,
UBound(A, 2) - LBound(A, 2) + 1
calculates the size of the second dimension of array A. - The Option Base setting does not affect the return value of the UBound function. Using the To clause when declaring an array with any of the variable declaration statements (Dim, Private, Public, ReDim, Static) will cause the number specified in the declaration to be set as the upper bound. The value specified in the To clause takes precedence over the Option Base setting. (This is illustrated in the example).
Example
Dim Upper
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' Declare a variable containing an array
Dim AnyArray(10)
Upper = UBound(MyArray, 1) ' Returns: 10.
Upper = UBound(MyArray, 3) ' Returns: 20.
Upper = UBound(AnyArray) ' Returns: 10.
Choose Function
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
Choose |
Choose(index, choice-1, [choice-2, ..., [choice-n]]) |
Returns one of the arguments from choice-1 to choice-n based on the index argument. | Choose(1, "Speedy", "United", "Federal") |
Speedy |
- The index argument is numeric and must be between 1 and the number of choice arguments.
- The choice arguments can be any Variant expressions containing one of the possible choices.
- If the index argument is greater than the number of choices, the function returns Null.
CreateObject Function
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
CreateObject |
CreateObject(class, [servername]) |
Creates and returns a reference to an ActiveX object. | Set ExcelSheet = CreateObject("Excel.Sheet") |
Creates an object representing an Excel worksheet. |
- The class argument is the name of the application and the class of the object to be created. The syntax for this argument is appname.objecttype and consists of two parts: appname (the name of the application providing the object) and objecttype (the type or class name of the object to create).
- The optional servername argument is the name of the network server where the object is to be created. (Use this if you want to create the object on a computer on the network).
- After an object is created by the function, the created object will have all the methods and properties of the referenced object of which it is an instance.
The process of connecting the object created by the CreateObject function happens at runtime. This is because to create an object using this function, a variable is first declared using the As Object clause, meaning the variable can hold a reference to any type of object; therefore, access to the object is only possible at runtime. This type of variable is called Late-Bound. The opposite type is early-bound. The reference of an early-bound variable is specified at declaration and after declaration can only contain the reference of the declared object, but it performs better than a Late-Bound variable.
VarType Function
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
VarType |
VarType(varname) |
Returns an Integer value indicating the subtype of a variable or the default property type of an object. | MyCheck = VarType(StrVar) |
Returns the value 8 |
- The built-in VarType function is used to determine the data type of a variable. If you use an object instead of a variable in the function argument, the function will return the data type of the object’s default property (Property).
- The table below shows the data type corresponding to the return value of the VarType function.
| Constant | Value | Description |
|---|---|---|
vbEmpty |
0 | Empty (uninitialised) |
vbNull |
1 | Null (no valid data) |
vbInteger |
2 | Integer |
vbLong |
3 | Long integer |
vbSingle |
4 | Single-precision floating-point number (Wikipedia) |
vbDouble |
5 | Double-precision floating-point number (Wikipedia) |
vbCurrency |
6 | Currency value |
vbDate |
7 | Date value |
vbString |
8 | String |
vbObject |
9 | Object |
vbError |
10 | Error value |
vbBoolean |
11 | Boolean value |
vbVariant |
12 | Variant (used only with arrays of variants) |
vbDataObject |
13 | Data access object (DAO) |
vbDecimal |
14 | Decimal value |
vbByte |
17 | Byte value |
vbLongLong |
20 | LongLong integer (Valid only on 64-bit platforms) |
vbUserDefinedType |
36 | User-defined type |
vbArray |
8192 | Array |
IsNumeric Function
| Function | Syntax | Purpose | Example | Result |
|---|---|---|---|---|
IsNumeric |
IsNumeric(expression) |
Returns a Boolean value indicating whether the expression provided in the function argument can be evaluated as a number. | MyCheck = IsNumeric("55") |
Returns True |
The return value of the built-in IsNumeric function is True if the function argument is a number, otherwise False.
📚 Summary
In this article, we have familiarised ourselves with the most important VBA Built-in Functions. These functions are fundamental tools for building efficient and professional macros in Excel and other Office applications.
In future tutorials, we will cover String, Date & Time, File & System functions, as well as Error Handling functions in VBA in more detail.
Frequently Asked Questions about VBA Functions
What are VBA Built-in Functions?
Built-in Functions in VBA are a set of ready-made functions embedded by Microsoft within the VBA environment, used for common tasks such as calculations, text processing, date management, and error handling.
What is the difference between Sub and Function in VBA?
In VBA, a Sub procedure is a set of commands that executes but does not return a value, whereas a Function executes commands and also returns an output value. Functions are typically used for calculating or processing data.
How can I use built-in functions in VBA?
To use built-in functions, simply call the function name within a VBA procedure. For example, the Abs(-5) function returns the absolute value of 5, and the Len("Excel") function calculates the length of the string.
What is the difference between the Int and Fix functions in VBA?
Both functions are used to remove the fractional part of a number, but Int always rounds the number down (e.g., Int(-8.9) equals -9) whereas Fix simply truncates the fractional part (i.e., Fix(-8.9) equals -8).
How can I change the data type in VBA?
Using data type conversion functions such as CInt, CDbl, CStr, and CLng, you can convert a variable’s value to the desired type. For example, CStr(123) converts the number to a string.
How can I work with strings in VBA?
Functions such as Len, Left, Right, Mid, InStr, and Replace are used for string processing. With them, you can extract or replace parts of a string.
How can I get the current date and time in VBA?
The Date() function returns the system date and the Now() function returns the current date and time. To display only the time, you can use Time().
How do I calculate the difference between two dates in VBA?
Using the DateDiff() function, you can calculate the difference between two dates in days, months, or years. Example:
DateDiff("d", #1/1/2024#, Date) returns the difference in days until today.
How can I work with files in VBA?
Functions such as Dir(), Kill(), FileLen(), and GetAttr() are used for file management. For example, Dir("C:\Report.xlsx") checks whether the file exists.
What is the purpose of the Err object in VBA?
The Err object is used to identify and manage runtime errors. With properties such as Err.Number, Err.Description, and Err.Source, you can view error details and clear them with Err.Clear.
Can I use Excel functions in VBA?
Yes. Using the Application.WorksheetFunction object, you can call many Excel functions such as Sum or VLookup in VBA. Example:
MsgBox Application.WorksheetFunction.Sum(1,2,3)
Resources for Further Reading:
List of Built-in Functions on the Microsoft site
Read More
VBA Procedures | Definition, Types & Usage in Visual Basic
Constants in VBA | Types, Scope, and How to Use Them Effectively
Variable Scope in VBA | How to Access Variables across Different Parts of a Project
VBA Modules | Types of Modules and the Difference Between a Module and a Class
Operator Precedence in VBA | Order of Arithmetic and Logical Operations with Examples
VBA Operators | Performing Data Operations and Building Expressions