Byval vba excel описание

VBA Byval

Excel VBA ByVal

In VBA, we have a statement called ByVal which is used for calling the value from the subprocedure when the main procedure value is down to 0 or in other words when the value is reset. Where ByVal stands for By Value, which means replacing the main value by the value of another subprocedure. Excel VBA ByVal is the reference of linking once sub procedure with others so that we can use the linked sub procedure’s value by calling it using By Val. We can also give the reference of the value using ByRef. ByVal is used when we want to call a value from another sub procedure, but we do not want to change the value of argument whereas ByRef is used when we want to change the value using subprocedure.

VBA ByVal does not have any specific syntax which we need to follow. But the correct position of ByVal in VBA code will definitely make complete sense out of it. The above explanation would be much clear using the example shown below.

How to Use ByVal Statement in VBA Excel?

We will learn how to use a ByVal Statement in Excel by using the VBA Code.

You can download this VBA ByVal Excel Template here – VBA ByVal Excel Template

Example #1

To know the values from other subprocedures, when the main procedure value is down to 0 or in other words when the value is reset. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Write the subprocedure in the name of the performed operations or any name.

Code:

Sub VBA_ByVal()

End Sub

VBA Byval Example 1-2

Step 3: Define a variable as Integer using DIM as shown below.

Code:

Sub VBA_ByVal()

Dim A As Integer

End Sub

VBA Byval Example 1-3

Step 4: Assign a number to defined variable A. We are choosing number 10.

Code:

Sub VBA_ByVal()

Dim A As Integer
A = 10

End Sub

VBA Byval Example 1-4

Step 5: Use the message box to see the value stored in variable A.

Code:

Sub VBA_ByVal()

Dim A As Integer
A = 10
MsgBox A

End Sub

VBA Byval Example 1-5

Step 6: Now after that, we will be writing another sub procedure, by that we will be calling another value for the same variable.

Code:

Sub VBA_ByVal()

Dim A As Integer
A = 10
MsgBox A

End Sub

Sub Val_Section(ByVal A As Integer)

End Sub

VBA Byval Example 1-6

Step 7: Then we will use the same variable A and add any number to see the change in value from the main procedure.

Code:

Sub VBA_ByVal()

Dim A As Integer
A = 10
MsgBox A

End Sub

Sub Val_Section(ByVal A As Integer)

A = A + 12

End Sub

VBA Byval Example 1-7

Step 8: Now we will compile the code by pressing the F8 function key. We will see, as the compiler reaches the variable A, hovering the cursor there will reflect the value as 0 which is the initial value.

VBA Byval Example 1-8

Step 9: And once the cursor reaches at message box, then the value will be changed to 10 as now code has compiled till that.

VBA Byval Example 1-9

Step 10: Now run the code by pressing function key F5 and to run the code, click on the Play button located below the menu bar, the message box will give us the value as 10.

Message Box Example 1-10

Step 11: Now to call the value from below written sub procedure to the main procedure, use Val_Section which is our 2nd subprocedure name with variable A.

Code:

Sub VBA_ByVal()

Dim A As Integer
A = 10
MsgBox A
Val_Section A

End Sub

Sub Val_Section(ByVal A As Integer)

A = A + 12

End Sub

Integer Example 1-11

Step 12: Now if again compile the code using the F8 key and we will notice once the compiler reaches End Sub of 2nd sub procedure, on hovering the cursor there we will see the variable A has now the summed value as 22 adding the number from both the subprocedures.

VBA Byval Example 1-12

Example #2

There is another method to call the value from other sub procedure to the main procedure. For this, follow the below steps:

Step 1: For this, we will be using the same first half of the code as shown below.

Code:

Sub VBA_Byval2()

Dim A As Integer
A = 10
MsgBox A

End Sub

VBA Byval Example 2-1

Step 2: Now continuing the code, start the subprocedure for ByVal again as Integer.

Code:

Sub VBA_Byval2()

Dim A As Integer
A = 10
MsgBox A

End Sub

Sub Val_Section(ByVal A As Integer)

End Sub

Integer Example 2-2

Step 3: Here we will choose a different value which we want to call in the same variable A as 15.

Code:

Sub VBA_Byval2()

Dim A As Integer
A = 10
MsgBox A

End Sub

Sub Val_Section(ByVal A As Integer)

A = 15

End Sub

VBA Byval Example 2-3

Step 4: Now to call the value mentioned in 2nd sub procedure, we will use word CALL with the name of 2nd sub procedure with variable A as shown below in the first part of the code.

Code:

Sub VBA_Byval2()

Dim A As Integer
A = 10
MsgBox A
Call Val_Section(A)

End Sub

Sub Val_Section(ByVal A As Integer)

A = 15

End Sub

VBA Byval Example 2-4

Step 5: Similar to the procedure shown in example-1, compile the code using F8 step by step. We will see, as the compiler compiles the first subprocedure, we will get the message box with number 10 which we have used in variable A.

Message Box Example 2-5

Continuing the compiling, as we reach at value 15 of variable A from the 2nd sub procedure, then hovering the cursor will reflect the value as 10 which is the same as 1st subprocedure.

And at last when our compiler reaches at End Sub then it will reflect the value as 15 after hovering the cursor, which is now called by using ByVal operation in the first subprocedure. But the message will only reflect the value as 10.

Pros & Cons of VBA ByVal

Below are the pros and cons of VBA ByVal:

  • It is very easy to implement the ByVal even using the simple code of storing any number.
  • We can pass any number as per the data type used with the limit range.
  • VBA ByVal doesn’t reflect the updated or called value from the other sub procedure through the message box. It carries the same value even the message box pops up multiple times.

Things to Remember

  • VBA ByVal and ByRef both are used for giving the reference. But the ByRef is only used for giving the reference whereas ByVal is used for calling the values stored in a different subprocedure.
  • Hover the cursor at the variable name only to see the current position of value. Even after the compiler passes from there, the updated value will be seen only by hovering the cursor at the exact position.
  • VBA ByVal carries the same value there in the first subprocedure once the code is run. And whatever changes happen when we call the value using ByVal, it will again reset to the previous value only.
  • Once we are done with writing the code, always remember to save the code in Macro enabled excel format which is used for saving VBA Code.

Recommended Articles

This is a guide to the VBA ByVal. Here we discuss how to use ByVal Statement in excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. How to Use VBA Login?
  2. VBA Month | Examples With Excel Template
  3. How to Use Create Object Function in VBA Excel?
  4. How to Use VBA IsError Function?

Excel VBA ByVal Function Argument

ByVal is a statement in VBA. ByVal stands for “By Value,” i.e., when the subprocedure calls in from the procedure, the value of the variables is reset to the new value from the new procedure called in.

In VBA, when we work with functions that call in different functions, there are certain circumstances that the value for the original argument is changed when calls the function. The ByVal statement prohibits the procedure or the code from changing the value for the argument.

By reading the explanation, we know it is not easy to understand. But with practical examples of function, we can understand it better.

Table of contents
  • Excel VBA ByVal Function Argument
    • How to use ByVal Argument in VBA?
      • Example #1
      • Example #2
    • Things to Remember
    • Recommended Articles

VBA-ByVal

How to use ByVal Argument in VBA?

You can download this VBA ByVal Excel Template here – VBA ByVal Excel Template

Example #1

Look at the VBA codesVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more below.

Code:

Sub Macro1()

    Dim k As Integer

    k = 50

    Macro2 k

    MsgBox k

End Sub
Sub Macro2(ByVal k As Integer)

    k = k + 5

End Sub

VBA Byval -Example 1

The above two macro procedures have a common variable, “k,” across procedures. Let me explain this in detail before we see the result.

In the first Macro, we have assigned the value of 50 to the variable “k.”

Dim k As Integer

k = 50

Next, we have called the second macro procedure from the first Macro.

Macro2 k

In Macro2, we have reset the variable’s value to k = k + 5. In this macro, we have used the ByVal argument to assign the value to the variable “k.”

Now, to understand “ByVal,” let’s run the VBA code by pressing the F8 key.

#1 – Upon pressing the F8 key first, it will highlight the first line of the Macro1.

VBA Byval -Example 1.1

At this point, place a cursor on the variable “k.” It should show the value of the variable “k.”

VBA Byval -Example 1.2

At the moment, the value of “k” is zero.

#2 – Press the F8 key again, and it will jump to the third line.

VBA Byval -Example 1.3

Even now, the value of “k” is still zero.

#3 – Press the F8 key now. See the value of the k.

Example 1.4

Since the “k” value sets to 50 and the code executes, the value shows as 50.

#4 – The highlighted line is “Macro2 k,” i.e., pressing the F8 key will jump to the second procedure, Macro2.

Example 1.5

#5 – Even now, the value of variable “k” in this procedure also shows as 50. But inside this macro, we are resetting the value of the variable “k” as k = k + 5, i.e., 55. So, now press the F8 key two more times.

Example 1.6

As you can see above, the “k” value is 55 now.

#6 – Press the F8 key. It will jump back to the Macro1 procedure.

Example 1.7

When the macro jumps back to the original procedure Macro1, our variable “k” value is no longer 55 but rather the original value in this procedure, i.e., 50.

When you press the F8 key, we can see only 50 in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

VBA Byval Output 1

As we have told at the beginning of the article “ByVal,” the argument does not carry values from one procedure to another even though it carries the variable’s value from the first macro to the second by the moment. It encounters the line “ByVal” when it returns to the original macro. It resets the value to the original value in the procedure only.

Example #2

Now, take a look at the below two macros.

Code:

Sub P1()

    Dim k As Integer: k = 10

    Call P2(k)

    MsgBox k

End Sub
Sub P2(ByVal k As Integer)

     k = 15

End Sub

Example 2.1

  • It is similar to the first example. In the macro “P1,” we have assigned the value of 10 to the variable “k,” and in the same macro “P1,” we have called the second macro “P2” with variable “k.”
  • In the second macro, “P2,” we have used the ByVal argument. This time, the value of variable “k” is 15.

This macro carries the value of variable “k” as ten from macro “P1” to macro “P2.So, this macro will reset the value to 15, but the moment it comes back to finish the macro to the first macro, “P1,the value of “k” back to 10, not 15.

VBA Byval Output 2

Things to Remember

The ByVal argument does not affect the variable value even after running the macro. Still, we can carry the variable’s value from one macro to the other with the By Ref argument.

Recommended Articles

This article has been a guide to VBA Byval. Here, we discuss using the ByVal argument in VBA along with the examples and downloadable Excel template. You can learn more about VBA from the following articles: –

  • VBA ByRef Argument Type Mismatch
  • VBA Split String into Array
  • Set Range in VBA
  • VBA Examples

Содержание

  1. Function statement
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. VBA-Урок 9. Процедуры и функции
  8. Public — Private
  9. Запуск процедуры с середины другой процедуры
  10. Аргументы
  11. Необязательные аргументы
  12. ByRef — ByVal
  13. Функции
  14. Sub statement
  15. Syntax
  16. Remarks
  17. Example
  18. See also
  19. Support and feedback

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.

Источник

VBA-Урок 9. Процедуры и функции

Public — Private

На данный момент, все процедуры, мы создавали, имеют тип Public , что означает, что они доступны из любого модуля.

Чтобы сделать процедуру доступной только в определенном модуле, используется ключевое слово Private:

Запуск процедуры с середины другой процедуры

Чтобы выполнить процедуру с середины другой процедуры, просто введите ее название.

Здесь есть очень простой пример:

Аргументы

Аргументы делают возможным использование значений из процедуры в под-процедуры (запомните, что по умолчанию, переменные являются доступны только по той процедуры, в которой они были объявлены).

К процедуре «warning» был добавлен аргумент, в данном случае это переменная «var_text» с типом «String» (строка):

Эта процедура требует аргумент, поэтому мы должны поставить значение после «warning», чтобы выполнить ее:

Когда мы хотим прописать несколько аргументов, тогда они должны быть отделены запятыми.

Необязательные аргументы

По умолчанию, если процедура имеет аргументы, то они должны быть обязательно проставлены, и если они не проставлены, тогда процедура не выполнится.

Необязательный аргумент может быть добавлен после обязательного, с помощью ключевого слова Optional . Например:

Теперь эта процедура может быть выполнена с или без опционального аргумента, как здесь:

Аргументы должны быть введены в правильном порядке.

Чтобы протестировать, присутствует ли опциональный аргумент в процедуре, мы используем функцию IsMissing . Эта функция совместима только с некоторыми типами функций (типа Variant) и это является решающим, так как тип необязательно аргументов не был указан в объявлении (необъявленный тип = Variant).

Здесь есть пример, который использует два фрагмента кода, которые рассматривались выше:

См. рисунок ниже (пример 1):

ByRef — ByVal

По умолчанию, аргументы имеют тип ByRef , что означает: если переменная передается как аргумент, ссылка на нее будет также передаваться. Иными словами, если переменная была изменена другой под-процедурой, то она также будет изменена во внешней процедуре, которая вызывает эту под-процедуру.

Чтобы стало понятнее, ниже есть пример того, что произойдет, если макрос будет запущен на выполнение:

Второй метод заключается в использовании ByVal .

В отличие от ByRef , который передает ссылки (ярлык), ByVal передает значение, которое означает, что значение передано как аргумент не было изменено.

Ниже вы можете увидеть как предыдущий код и ByVal работают:

Что вам нужно запомнить: используйте ByVal когда переменная не должна быть изменена .

Функции

Основным отличием между процедурой и функцией является то, что функция возвращает значение.

Вот простой пример:

Функция может быть использована на рабочем листе, подобно любой другой функции в Excel.

Например, чтобы получить квадрат значения, которое введенное в ячейку A1:

Источник

Sub statement

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

Syntax

[ Private | Public | Friend ] [ Static ] Sub name [ ( arglist ) ]
[ statements ]
[ Exit Sub ]
[ statements ]
End Sub

The Sub statement syntax has these parts:

Part Description
Public Optional. Indicates that the Sub procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.
Private Optional. Indicates that the Sub 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 Sub procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static Optional. Indicates that the Sub procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Sub, even if they are used in the procedure.
name Required. Name of the Sub; follows standard variable naming conventions.
arglist Optional. List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.
statements Optional. Any group of statements to be executed within the Sub procedure.

The arglist argument has the following syntax and parts:

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

Part Description
Optional Optional. Keyword indicating 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. ParamArray can’t 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, Sub 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 doesn’t appear in the type library of its parent class, nor can a Friend procedure be late bound.

Sub 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 is not used with recursive Sub procedures.

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

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

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can’t be used in an expression.

You call a Sub procedure by using the procedure name followed by the argument list. See the Call statement for specific information about how to call Sub procedures.

Variables used in Sub 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 is referring to that module-level name. To avoid this kind of conflict, explicitly declare variables. Use an Option Explicit statement to force explicit declaration of variables.

You can’t use GoSub, GoTo, or Return to enter or exit a Sub procedure.

Example

This example uses the Sub statement to define the name, arguments, and code that form the body of a Sub procedure.

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.

Источник

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

Понравилась статья? Поделить с друзьями:
  • Byte word and dword
  • Calculate percentage for excel
  • Byte to word delphi
  • Calculate percent in excel
  • Byte to word convert