Excel vba function calls

In this Article

  • Creating a Function without Arguments
  • Calling a Function from a Sub Procedure
  • Creating Functions
    • Single Argument
    • Multiple Arguments
    • Optional Arguments
    • Default Argument Value
    • ByVal and ByRef
  • Exit Function
  • Using a Function from within an Excel Sheet

This tutorial will teach you to create and use functions with and without parameters in VBA

VBA contains a large amount of built-in functions for you to use, but you are also able to write your own.   When you write code in VBA, you can write it in a Sub Procedure, or a Function Procedure. A Function Procedure is able to return a value to your code.  This is extremely useful if you want VBA to perform a task to return a result. VBA functions can also be called from inside Excel, just like Excel’s built-in Excel functions.

Creating a Function without Arguments

To create a function you need to define the function by giving the function a name. The function can then be defined as a data type indicating the type of data you want the function to return.

You may want to create a function that returns a static value each time it is called – a bit like a constant.

Function GetValue() As Integer
   GetValue = 50
End Function

If you were to run the function, the function would always return the value of 50.

vba function no argument

You can also create functions that refer to objects in VBA but you need to use the Set Keyword to return the value from the function.

Function GetRange() as Range
  Set GetRange = Range("A1:G4")
End Function

If you were to use the above function in your VBA code, the function would always return the range of cells A1 to G4 in whichever sheet you are working in.

Calling a Function from a Sub Procedure

Once you create a function, you can call it from anywhere else in your code by using a Sub Procedure to call the function.

vba function no argument 1

The value of 50 would always be returned.

You can also call the GetRange function from a Sub Procedure.

vba function no argument range

In the above example, the GetRange Function is called by the Sub Procedure to bold the cells in the range object.

Creating Functions

Single Argument

You can also assign a parameter or parameters to your function.  These parameters can be referred to as Arguments.

Function ConvertKilosToPounds (dblKilo as Double) as Double
   ConvertKiloToPounds = dblKilo*2.2
End Function

We can then call the above function from a Sub Procedure in order to work out how many pounds a specific amount of kilos are.

vba function return value

A function can be a called from multiple procedures within your VBA code if required.  This is very useful in that it stops you from having to write the same code over and over again.  It also enables you to divide long procedures into small manageable functions.

vba functions return values 1

In the above example, we have 2 procedures – each of them are using the Function to calculate the pound value of the kilos passed to them in the dblKilo Argument of the function.

Multiple Arguments

You can create a Function with multiple arguments and pass the values to the Function by way of a Sub Procedure.

Function CalculateDayDiff(Date1 as Date, Date2 as Date) as Double
   CalculateDayDiff = Date2-Date1
End Function

We can then call the function to calculate the amount of days between 2 dates.

vba-function-2-arguments

Optional Arguments

You can also pass Optional arguments to a Function.  In other words, sometimes you may need the argument, and sometimes you may not – depending on what code you are using the Function with .

Function CalculateDayDiff(Date1 as Date, Optional Date2 as Date) as Double
'check for second date and if not there, make Date2 equal to today's date.
   If Date2=0 then Date2 = Date
'calculate difference
   CalculateDayDiff = Date2-Date1 
End Function

vba function optional parameter

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Default Argument Value

You can also set the default value of the Optional arguments when you are creating the function so that if the user omits the argument, the value that you have put as default will be used instead.

Function CalculateDayDiff(Date1 as Date, Optional Date2 as Date="06/02/2020") as Double 
'calculate difference 
   CalculateDayDiff = Date2-Date1 
End Function

vba functions optional default

ByVal and ByRef

When you pass values to a function, you can use the ByVal or ByRef keywords.  If you omit either of these, the ByRef is used as the default.

ByVal means that you are passing a copy of the variable to the function, whereas ByRef means you are referring to the original value of the variable.  When you pass a  copy of the variable (ByVal), the original value of the variable is NOT changed, but when you reference the variable, the original value of the variable is changed by the function.

Function GetValue(ByRef intA As Integer) As Integer
   intA = intA * 4
   GetValue = intA
End Function

In the function above, the ByRef could be omitted and the function would work the same way.

Function GetValue(intA As Integer) As Integer
   intA = intA * 4
   GetValue = intA
End Function

To call this function, we can run a sub-procedure.

Sub TestValues()
   Dim intVal As Integer
'populate the variable with the value 10
   intVal = 10
'run the GetValue function, and show the value in the immediate window
   Debug.Print GetValue(intVal)
'show the value of the intVal variable in the immediate window 
   Debug.Print  intVal
End Sub

vba function by ref

Note that the debug windows show the value 40 both times.  When you pass the variable IntVal to the function – the value of 10 is passed to the function, and multiplied by 4.  Using the ByRef keyword (or omitting it altogether), will AMEND the value of the IntVal variable.   This is shown when you show first the result of the function in the immediate window (40), and then the value of the IntVal variable in the debug window (also 40).

If we do NOT want to change the value of the original variable, we have to use ByVal in the function.

Function GetValue(ByVal intA As Integer) As Integer
intA = intA * 4
GetValue = intA
End Function

Now if we call the function from a sub-procedure, the value of the variable IntVal will remain at 10.

vba function byval

Exit Function

If you create a function that tests for a certain condition, and once the condition is found to be true, you want return the value from the function, you may need to add an Exit Function statement in your Function in order to exit the function before you have run through all the code in that function.

Function FindNumber(strSearch As String) As Integer
   Dim i As Integer
'loop through each letter in the string
   For i = 1 To Len(strSearch)
   'if the letter is numeric, return the value to the function
      If IsNumeric(Mid(strSearch, i, 1)) Then
         FindNumber= Mid(strSearch, i, 1)
   'then exit the function
         Exit Function
      End If
   Next
   FindNumber= 0
End Function

The function above will loop through the string that is provided until it finds a number, and then return that number from the string.  It will only find the first number in the string as it will then Exit the function.

The function above can be called by a Sub routine such as the one below.

Sub CheckForNumber()
   Dim NumIs as Integer
'pass a text string to the find number function
   NumIs = FindNumber("Upper Floor, 8 Oak Lane, Texas")
'show the result in the immediate window
   Debug.Print NumIs
End Sub

vba function exit function

VBA Programming | Code Generator does work for you!

Using a Function from within an Excel Sheet

In addition to calling a function from your VBA code using a sub procedure, you can also call the function from within your Excel sheet.  The functions that you have created should by default appear in your function list in the User Defined section of the function list.

Click on the fx to show the Insert Function dialog box.

vba function fx

Select User Defined from the Category List

vba function udf

Select the function you require from the available User Defined Functions (UDF’s).

vba function excel sheet

Alternatively, when you start writing your function in Excel, the function should appear in the drop down list of functions.

vba function dropdown

If you do not want the function to be available inside an Excel sheet, you need to put the Private word in front of the word Function when you create the function in your VBA code.

Private Function CalculateDayDiff(Date1 as Date, Date2 as Date) as Double 
   CalculateDayDiff = Date2-Date1 
End Function

It will now not appear in the drop down list showing the Excel functions available.

vba function dropdown 2

Interestingly enough, however, you can still use the function – it just will not appear in the list when looking for it!

vba function excel

If you have declared the second argument as Optional, you can omit it within the Excel sheet as well as within the VBA code.

vba function excel 2

You can also use the a function that you have created without arguments in your Excel sheet.

vba function no argument excel

Skip to content

VBA code to call a function

Home » VBA » VBA code to call a function

The below example will help you to know how to call a function in Excel VBA Macros (it can be Excel VBA function, or user defined function). We generally create lot of function and we use the functions whenever and any time we want. The below example will help you to understand calling a simple function with and without parameters.

Calling a function Excel VBA

Here is the simple example to call the Now function to display the time. We use the Now function to get the System Current Time and Date.

'vba code to call a function
Sub vba_code_to_call_a_function()
    MsgBox Now()
End Sub

Calling a function Excel VBA: Function with Parameters

Here is the another example to call the Left function to extract the left part of a string. We use the left function to extract the left part of any string.

'vba code to call a function
Sub vba_code_to_call_a_function_a()
    MsgBox Left("123", 2)
End Sub

Calling a user defined Function Excel VBA

It is same as above, but we have to make sure that the functions is written before calling the function. Other wise it will though the run time error.

'User Defined Function
Function mySum(ByVal A As Integer, ByVal B As Integer)
    mySum = A + B
End Function

'vba code to call a the user defined function
Sub vba_code_to_call_a_function_b()
    'Calling udf
    MsgBox mySum(1, 5)
End Sub

VBA code to Convert and Save the Excel to CSV – Instructions

Please follow the below step by step instructions to test this Example VBA Macro codes:

  • Step 1: Open a New Excel workbook
  • Step 2: Press Alt+F11 – This will open the VBA Editor (alternatively, you can open it from Developer Tab in Excel Ribbon)
  • Step 3: Insert a code module from then insert menu of the VBE
  • Step 4: Copy the above code and paste in the code module which have inserted in the above step
  • Step 5: Now press F8 to debug the Macro to check how the VBA is calling the function while execution
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • Calling a function Excel VBA
  • Calling a function Excel VBA: Function with Parameters
  • Calling a user defined Function Excel VBA
    • VBA code to Convert and Save the Excel to CSV – Instructions

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

One Comment

  1. Rajadurai16
    March 16, 2017 at 4:18 PM — Reply

    Timer vba codes

    Dim binNew As Boolean
    Dim TRows, THows, i As Long

    Private Sub UserForm_Click()

    End Sub

    Private Sub CmdClose_Click()
    If CmdClose.Caption = “Close” Then
    Unload Me
    Else
    CmdClose.Caption = “Close”
    CmdNew.Enabled = True
    CmdDelete.Enabled = True
    End If
    End Sub

    Private Sub CmdNew_Click()
    binNew = True
    txtEmpNo.Text = ”
    txtEmpName.Text = ”
    txtAddr1.Text = ”
    txtAddr2.Text = ”
    txtAddr3.Text = ”

    CmdClose.Caption = “Cancel”
    CmdNew.Enabled = False
    CmdSave.Enabled = True
    CmdDelete.Enabled = False
    End Sub

    Private Sub cmdSave_Click()
    If Trim(txtEmpNo.Text) = ” Then
    MsgBox “Enter Emp. No. “, vbCritical, “Save”
    Exit Sub
    End If
    Call prSave
    End Sub

    Private Sub prSave()
    If binNew = True Then
    THows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
    With Worksheets(“Data”).Range(“A1″)
    .Offset(THows, 0).Value = txtEmpNo.Text
    .Offset(THows, 1).Value = txtEmpName.Text
    .Offset(THows, 2).Value = txtAddr1.Text
    .Offset(THows, 3).Value = txtAddr2.Text
    .Offset(THows, 4).Value = txtAddr3.Text

    End With
    txtEmpNo.Text = ”
    txtEmpName.Text = ”
    txtAddr1.Text = ”
    txtAddr2.Text = ”
    txtAddr3.Text = ”

    Call PrComboBoxFill
    Else
    For i = 2 To TRows
    If Trim(Worksheets(“Data”).Cells(i, 1).Value) = Trim(ComboBox1.Text) Then
    Worksheets(“Data”).Cells(i, 1).Value = txtEmpNo.Text
    Worksheets(“Data”).Cells(i, 2).Value = txtEmpName.Text
    Worksheets(“Data”).Cells(i, 3).Value = txtAddr1.Text
    Worksheets(“Data”).Cells(i, 4).Value = txtAddr2.Text
    Worksheets(“Data”).Cells(i, 5).Value = txtAddr3.Text

    txtEmpNo.Text = ”
    txtEmpName.Text = ”
    txtAddr1.Text = ”
    txtAddr2.Text = ”
    txtAddr3.Text = ”

    Exit For
    End If
    Next i
    End If
    binNew = False

    End Sub
    ————————————-
    Private Sub cmdDelete_Click()
    TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
    Dim strDel
    strDel = MagBox(“Delete ?”, vbYesNo, “Delete”)
    If strDel = vbYes Then
    For i = 2 To TRows
    If Trims(Worksheets(“Data”).Cells(i, 1).Value) = Trim(ComboBox1.Text) Then

    ‘ sheet1.range(i & “:” & i).Delete
    Worksheets(“Data”).Range(i & “:” & i).Delete

    TxtEmpNo.Text = ”
    txtEmpName.Text = ”
    TxtempAddr1.Text = ”
    TxtempAddr2.Text = ”
    TxtempAddr3.Text = ”
    TxtempAddr4.Text = ”
    Call prCoboBoxFill
    Exit For
    End If
    Next i
    If Trim(ComboBox1.Text) = ” Then
    cmdSave.Enabled = False
    cmdDelete.Enabled = False
    Else
    cmdSave.Enabled = True
    cmdDelete.Enabled = True
    End If
    End If
    End Sub
    ——————————–
    Private Sub CmdClose_Click()
    If CmdClose.Caption = “Close” Then
    Unload Me
    Else
    CmdClose.Caption = “Close”
    CmdNew.Enabled = True
    CmdDelete.Enabled = True
    End If
    End Sub
    ————————————-

    Private Sub PrComboBoxFill()
    TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
    ComboBox1.Clear
    For i = 2 To TRows
    ComboBox1.AddItem Worksheets(“Data”).Cells(i, 1).Value

    Next i
    End Sub
    —————————————————–
    Private Sub Userform_Initialize()
    Call PrComboBoxFill

    CmdSave.Enabled = False
    CmdDelete.Enabled = False

    End Sub
    —————————————————–
    Private Sub cmdsearch_Click()
    binNew = False
    txtEmpNo.Text = ”
    txtEmpName.Text = ”
    txtAddr1.Text = ”
    txtAddr2.Text = ”
    txtAddr3.Text = ”

    TRows = Worksheets(“Data”).Range(“A1”).CurrentRegion.Rows.Count
    For i = 2 To TRows
    If Val(Trim(Worksheets(“Data”).Cells(i, 1).Value)) = Val(Trim(ComboBox1.Text)) Then

    txtEmpNo.Text = Worksheets(“Data”).Cells(i, 1).Value
    txtEmpName.Text = Worksheets(“Data”).Cells(i, 2).Value
    txtAddr1.Text = Worksheets(“Data”).Cells(i, 3).Value
    txtAddr2.Text = Worksheets(“Data”).Cells(i, 4).Value
    txtAddr3.Text = Worksheets(“Data”).Cells(i, 5).Value

    Exit For
    End If
    Next i
    If txtEmpNo.Text = ” Then
    Else
    CmdSave.Enabled = True
    CmdDelete.Enabled = True
    End If
    End Sub

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Содержание

  1. Function statement
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. Call statement
  8. Syntax
  9. Remarks
  10. Example
  11. See also
  12. Support and feedback
  13. VBA Function – Call, Return Value, & Parameters
  14. Creating a Function without Arguments
  15. Calling a Function from a Sub Procedure
  16. Creating Functions
  17. Single Argument
  18. Multiple Arguments
  19. Optional Arguments
  20. VBA Coding Made Easy
  21. Default Argument Value
  22. ByVal and ByRef
  23. Exit Function
  24. Using a Function from within an Excel Sheet
  25. VBA Code Examples Add-in

Function statement

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Public | Private | Friend] [ Static ] Function name [ ( arglist ) ] [ As type ]
[ statements ]
[ name = expression ]
[ Exit Function ]
[ statements ]
[ name = expression ]
End Function

The Function statement syntax has these parts:

Part Description
Public Optional. Indicates that the Function procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private, the procedure is not available outside the project.
Private Optional. Indicates that the Function procedure is accessible only to other procedures in the module where it is declared.
Friend Optional. Used only in a class module. Indicates that the Function procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static Optional. Indicates that the Function procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Function, even if they are used in the procedure.
name Required. Name of the Function; follows standard variable naming conventions.
arglist Optional. List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas.
type Optional. Data type of the value returned by the Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (except fixed length), Object, Variant, or any user-defined type.
statements Optional. Any group of statements to be executed within the Function procedure.
expression Optional. Return value of the Function.

The arglist argument has the following syntax and parts:

[ Optional ] [ ByVal | ByRef ] [ ParamArray ] varname [ ( ) ] [ As type ] [ = defaultvalue ]

Part Description
Optional Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared by using the Optional keyword. Optional can’t be used for any argument if ParamArray is used.
ByVal Optional. Indicates that the argument is passed by value.
ByRef Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname Required. Name of the variable representing the argument; follows standard variable naming conventions.
type Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported) Date, String (variable length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

If not explicitly specified by using Public, Private, or Friend, Function procedures are public by default.

If Static isn’t used, the value of local variables is not preserved between calls.

The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure does not appear in the type library of its parent class, nor can a Friend procedure be late bound.

Function procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually isn’t used with recursive Function procedures.

All executable code must be in procedures. You can’t define a Function procedure inside another Function, Sub, or Property procedure.

The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, you can use a Function procedure on the right side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure by using the function name, followed by the argument list in parentheses, in an expression. See the Call statement for specific information about how to call Function procedures.

To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string («»), and a Variant function returns Empty. A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following example shows how to assign a return value to a function. In this case, False is assigned to the name to indicate that some value was not found.

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not.

Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that your procedure refers to that module-level name. Explicitly declare variables to avoid this kind of conflict. Use an Option Explicit statement to force explicit declaration of variables.

Visual Basic may rearrange arithmetic expressions to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression. For more information about arithmetic operators, see Operators.

Example

This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure. The last example uses hard-typed, initialized Optional arguments.

Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, it is passed by value.

Optional arguments can have default values and types other than Variant.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Call statement

Transfers control to a Sub procedure, Function procedure, or dynamic-link library (DLL) procedure.

Syntax

[ Call ] name [ argumentlist ]

The Call statement syntax has these parts:

Part Description
Call Optional; keyword. If specified, you must enclose argumentlist in parentheses.

For example: Call MyProc(0)

name Required. Name of the procedure to call.
argumentlist Optional. Comma-delimited list of variables, arrays, or expressions to pass to the procedure. Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are treated by the called procedure.

However, ByVal and ByRef can be used with Call only when calling a DLL procedure. On the Macintosh, ByVal and ByRef can be used with Call when making a call to a Macintosh code resource.

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function’s return value is discarded.

To pass a whole array to a procedure, use the array name followed by empty parentheses.

Example

This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, and a dynamic-link library (DLL) procedure. DLLs are not used on the Macintosh.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Function – Call, Return Value, & Parameters

In this Article

This tutorial will teach you to create and use functions with and without parameters in VBA

VBA contains a large amount of built-in functions for you to use, but you are also able to write your own. When you write code in VBA, you can write it in a Sub Procedure, or a Function Procedure. A Function Procedure is able to return a value to your code. This is extremely useful if you want VBA to perform a task to return a result. VBA functions can also be called from inside Excel, just like Excel’s built-in Excel functions.

Creating a Function without Arguments

To create a function you need to define the function by giving the function a name. The function can then be defined as a data type indicating the type of data you want the function to return.

You may want to create a function that returns a static value each time it is called – a bit like a constant.

If you were to run the function, the function would always return the value of 50.

You can also create functions that refer to objects in VBA but you need to use the Set Keyword to return the value from the function.

If you were to use the above function in your VBA code, the function would always return the range of cells A1 to G4 in whichever sheet you are working in.

Calling a Function from a Sub Procedure

Once you create a function, you can call it from anywhere else in your code by using a Sub Procedure to call the function.

The value of 50 would always be returned.

You can also call the GetRange function from a Sub Procedure.

In the above example, the GetRange Function is called by the Sub Procedure to bold the cells in the range object.

Creating Functions

Single Argument

You can also assign a parameter or parameters to your function. These parameters can be referred to as Arguments.

We can then call the above function from a Sub Procedure in order to work out how many pounds a specific amount of kilos are.

A function can be a called from multiple procedures within your VBA code if required. This is very useful in that it stops you from having to write the same code over and over again. It also enables you to divide long procedures into small manageable functions.

In the above example, we have 2 procedures – each of them are using the Function to calculate the pound value of the kilos passed to them in the dblKilo Argument of the function.

Multiple Arguments

You can create a Function with multiple arguments and pass the values to the Function by way of a Sub Procedure.

We can then call the function to calculate the amount of days between 2 dates.

Optional Arguments

You can also pass Optional arguments to a Function. In other words, sometimes you may need the argument, and sometimes you may not – depending on what code you are using the Function with .

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Default Argument Value

You can also set the default value of the Optional arguments when you are creating the function so that if the user omits the argument, the value that you have put as default will be used instead.

ByVal and ByRef

When you pass values to a function, you can use the ByVal or ByRef keywords. If you omit either of these, the ByRef is used as the default.

ByVal means that you are passing a copy of the variable to the function, whereas ByRef means you are referring to the original value of the variable. When you pass a copy of the variable (ByVal), the original value of the variable is NOT changed, but when you reference the variable, the original value of the variable is changed by the function.

In the function above, the ByRef could be omitted and the function would work the same way.

To call this function, we can run a sub-procedure.

Note that the debug windows show the value 40 both times. When you pass the variable IntVal to the function – the value of 10 is passed to the function, and multiplied by 4. Using the ByRef keyword (or omitting it altogether), will AMEND the value of the IntVal variable. This is shown when you show first the result of the function in the immediate window (40), and then the value of the IntVal variable in the debug window (also 40).

If we do NOT want to change the value of the original variable, we have to use ByVal in the function.

Now if we call the function from a sub-procedure, the value of the variable IntVal will remain at 10.

Exit Function

If you create a function that tests for a certain condition, and once the condition is found to be true, you want return the value from the function, you may need to add an Exit Function statement in your Function in order to exit the function before you have run through all the code in that function.

The function above will loop through the string that is provided until it finds a number, and then return that number from the string. It will only find the first number in the string as it will then Exit the function.

The function above can be called by a Sub routine such as the one below.

Using a Function from within an Excel Sheet

In addition to calling a function from your VBA code using a sub procedure, you can also call the function from within your Excel sheet. The functions that you have created should by default appear in your function list in the User Defined section of the function list.

Click on the fx to show the Insert Function dialog box.

Select User Defined from the Category List

Select the function you require from the available User Defined Functions (UDF’s).

Alternatively, when you start writing your function in Excel, the function should appear in the drop down list of functions.

If you do not want the function to be available inside an Excel sheet, you need to put the Private word in front of the word Function when you create the function in your VBA code.

It will now not appear in the drop down list showing the Excel functions available.

Interestingly enough, however, you can still use the function – it just will not appear in the list when looking for it!

If you have declared the second argument as Optional, you can omit it within the Excel sheet as well as within the VBA code.

You can also use the a function that you have created without arguments in your Excel sheet.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

What is a Function?

A function is a piece of code that performs a specific task and returns a result. Functions are mostly used to carry out repetitive tasks such as formatting data for output, performing calculations, etc.

Suppose you are developing a program that calculates interest on a loan. You can create a function that accepts the loan amount and the payback period. The function can then use the loan amount and payback period to calculate the interest and return the value.

Why use functions

The advantages of using functions are the same as the ones in the above section on why use subroutines.

Rules of naming functions

The rules for naming functions as the same as the ones in the above section on rules for naming subroutines.

VBA Syntax for declaring Function

Private Function myFunction (ByVal arg1 As Integer, ByVal arg2 As Integer)
    myFunction = arg1 + arg2
End Function

HERE in the syntax,

Code Action
  • “Private Function myFunction(…)”
  • Here the keyword “Function” is used to declare a function named “myFunction” and start the body of the function.
  • The keyword ‘Private’ is used to specify the scope of the function
  • “ByVal arg1 As Integer, ByVal arg2 As Integer”
  • It declares two parameters of integer data type named ‘arg1’ and ‘arg2.’
  • myFunction = arg1 + arg2
  • evaluates the expression arg1 + arg2 and assigns the result to the name of the function.
  • “End Function”
  • “End Sub” is used to end the body of the function

Function demonstrated with Example:

Functions are very similar to the subroutine. The major difference between a subroutine and a function is that the function returns a value when it is called. While a subroutine does not return a value, when it is called. Let’s say you want to add two numbers. You can create a function that accepts two numbers and returns the sum of the numbers.

  1. Create the user interface
  2. Add the function
  3. Write code for the command button
  4. Test the code

Step 1) User interface

Add a command button to the worksheet as shown below

VBA Functions and Subroutine

Set the following properties of CommanButton1 to the following.

S/N Control Property Value
1 CommandButton1 Name btnAddNumbers
2 Caption Add Numbers Function

Your interface should now appear as follows

VBA Functions and Subroutine

Step 2) Function code.

  1. Press Alt + F11 to open the code window
  2. Add the following code
Private Function addNumbers(ByVal firstNumber As Integer, ByVal secondNumber As Integer)
    addNumbers = firstNumber + secondNumber
End Function

HERE in the code,

Code Action
  • “Private Function addNumbers(…)”
  • It declares a private function “addNumbers” that accepts two integer parameters.
  • “ByVal firstNumber As Integer, ByVal secondNumber As Integer”
  • It declares two parameter variables firstNumber and secondNumber
  • “addNumbers = firstNumber + secondNumber”
  • It adds the firstNumber and secondNumber values and assigns the sum to addNumbers.

Step 3) Write Code that calls the function

  1. Right click on btnAddNumbers_Click command button
  2. Select View Code
  3. Add the following code
Private Sub btnAddNumbersFunction_Click()
    MsgBox addNumbers(2, 3)
End Sub

HERE in the code,

Code Action
“MsgBox addNumbers(2,3)”
  • It calls the function addNumbers and passes in 2 and 3 as the parameters. The function returns the sum of the two numbers five (5)

Step 4) Run the program, you will get the following results

VBA Functions and Subroutine

Download Excel containing above code

Download the above Excel Code

Summary:

  • A function is a piece of code that performs a specific task. A function returns a value after execution.
  • Both subroutines and functions offer code reusability
  • Both subroutines and functions help break down large chunks of code into small manageable code.

Понравилась статья? Поделить с друзьями:
  • Excel vba from text to number
  • Excel vba from string to integer
  • Excel vba from python
  • Excel vba formular1c1 with if
  • Excel vba formula если