Just setting the return value to the function name is still not exactly the same as the Java (or other) return
statement, because in java, return
exits the function, like this:
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;
}
In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:
Public Function test(ByVal x As Integer) As Integer
If x = 1 Then
test = 1 ' does not exit immediately. You must manually terminate...
Exit Function ' to exit
End If
' Still here? return 0 as default.
test = 0
' no need for an Exit Function because we're about to exit anyway.
End Function
Since this is the case, it’s also nice to know that you can use the return variable like any other variable in the method. Like this:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test <> 1 Then ' Test the currently set return value
test = 0 ' Reset the return value to a *new* value
End If
End Function
Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test > 0 Then
' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
' AND THE RESULT RESETTING THE RETURN VALUE.
test = test(test - 1)
End If
End Function
As You may know, in general in programming to return a result from function there is Return statement. Even Visual Basic has it. Unfortunately there is no such thing in VBA. In this article I’m going to show You how to return a result from VBA function.
Let’s start with function
For the purpose of this article I’ve created functionModulo, which is very similar to the Mod function.
Function functionModulo(x As Integer, y As Integer) As Boolean
Dim divisionRest As Double, divisionRestStatus As Integer
Let divisionRest = x / y - Fix(x / y)
If divisionRest > 0 Then
divisionRestStatus = 0
Else
divisionRestStatus = 1
End If
If divisionRestStatus = 1 Then
functionModulo = True
Else
functionModulo = False
End If
End Function
This function allows You to check if there is a divisibility between two numbers. If there is a rest from division the function returns False, if there is no any – function returns True.
So to describe the work of this function, I was using return word. But not as a statement in code. To return the result in VBA function You need to use the function name itself and put it a value.
functionModulo = True
Unfortunately the function not stops there and exits. It just go further.
As close as possible
I decided to modify this function to make it as similar to Return statement schema as possible.
So first of all I cut it a little bit.
Function functionModulo(x As Integer, y As Integer) As Boolean
Dim divisionRest As Double
Let divisionRest = x / y - Fix(x / y)
If divisionRest > 0 Then
functionModulo = False
Else
functionModulo = True
End If
End Function
Then I wanted to have the same effect after returning the result from function as Return statement brings.
Function functionModulo(x As Integer, y As Integer) As Boolean
Dim divisionRest As Double
Let divisionRest = x / y - Fix(x / y)
If divisionRest > 0 Then functionModulo = False: Exit Function
If divisionRest = 0 Then functionModulo = True
End Function
That’s why after returning the value I added Exit Function.
If divisionRest > 0 Then functionModulo = False: Exit Function
I was almost done, but also figured out that we can only check for valid values. This means that I could set False value at the beginning as default. One conditional less in code. Cleaner the code.
Function functionModulo(x As Integer, y As Integer) As Boolean
functionModulo = False
Dim divisionRest As Double: Let divisionRest = x / y - Fix(x / y)
If divisionRest = 0 Then functionModulo = True
End Function
Having nothing after the conditional for True value I decided to erase Exit Function statement. In this case it is not needed, but in general it is really good approach to simulate Return statement as from other programming languages.
To sum up
To avoid unnecessary conditionals put the default value at the beginning of the function. You can also do that in the end of the code, only if You simulate the Return statement in VBA – pass the result in the function name and Exit Function just right after that line.
I’m very advanced in VBA, Excel, also easily linking VBA with other Office applications (e.g. PowerPoint) and external applications (e.g. SAP). I take part also in RPA processes (WebQuery, DataCache, IBM Access Client Solutions) where I can also use my SQL basic skillset. I’m trying now to widen my knowledge into TypeScript/JavaScript direction.
View all posts by Tomasz Płociński
“Computers are useless. They can only give you answers.” – Pablo Picasso.
This post provides a complete guide to using the VBA Sub. I also cover VBA functions which are very similar to Subs.
If you want some quick information about creating a VBA Sub, Function, passing parameters, return values etc. then check out the quick guide below.
If you want to understand all about the VBA Sub, you can read through the post from start to finish or you can check out the table of contents below.
Quick Guide to the VBA Sub
Sub | Example |
---|---|
Sub
|
|
Function
|
|
Create a sub | Sub CreateReport()
End Sub |
Create a function | Function GetTotal() As Long
End Function |
Create a sub with parameters | Sub CreateReport(ByVal Price As Double)
Sub CreateReport(ByVal Name As String) |
Create a function with parameters | Function GetTotal(Price As Double)
Function GetTotal(Name As String) |
Call a sub | Call CreateReport ‘ Or CreateReport |
Call a function | Call CalcPrice ‘ Or CalcPrice |
Call a sub with parameters | Call CreateReport(12.99)
CreateReport 12.99 |
Call a function with parameters | Call CalcPrice(12.99)
CalcPrice 12.99 |
Call a function and retrieve value (cannot use Call keyword for this) |
Price = CalcPrice |
Call a function and retrieve object | Set coll = GetCollection |
Call a function with params and retrieve value/object | Price = CalcPrice(12) Set coll = GetCollection(«Apples») |
Return a value from Function | Function GetTotal() As Long GetTotal = 67 End Function |
Return an object from a function | Function GetCollection() As Collection Dim coll As New Collection Set GetCollection = coll End Function |
Exit a sub | If IsError(Range(«A1»)) Then Exit Sub End If |
Exit a function | If IsError(Range(«A1»)) Then Exit Function End If |
Private Sub/Private Function (available to current module) |
Private Sub CreateReport() |
Public Sub/Public Function (available to entire project) |
Public Sub CreateReport() |
Introduction
The VBA Sub is an essential component of the VBA language. You can also create functions which are very similar to subs. They are both procedures where you write your code. However, there are differences and these are important to understand. In this post I am going to look at subs and functions in detail and answer the vital questions including:
- What is the difference between them?
- When do I use a sub and when do I use a function?
- How do you run them?
- Can I return values?
- How do I pass parameters to them?
- What are optional parameters?
- and much more
Let’s start by looking at what is the VBA sub?
What is a Sub?
In Excel VBA a sub and a macro are essentially the same thing. This often leads to confusion so it is a good idea to remember it. For the rest of this post I will refer to them as subs.
A sub/macro is where you place your lines of VBA code. When you run a sub, all the lines of code it contains are executed. That means that VBA carries out their instructions.
The following is an example of an empty sub
Sub WriteValues() End Sub
You declare the sub by using the Sub keyword and the name you wish to give the sub. When you give it a name keep the following in mind:
- The name must begin with a letter and cannot contain spaces.
- The name must be unique in the current workbook.
- The name cannot be a reserved word in VBA.
The end of the Sub is marked by the line End Sub.
When you create your Sub you can add some code like the following example shows:
Sub WriteValues() Range("A1") = 6 End Sub
What is a Function?
A Function is very similar to a sub. The major difference is that a function can return a value – a sub cannot. There are other differences which we will look at but this is the main one.
You normally create a function when you want to return a value.
Creating a function is similar to creating a sub
Function PerformCalc() End Function
It is optional to add a return type to a function. If you don’t add the type then it is a Variant type by default. This means that VBA will decide the type at runtime.
The next example shows you how to specify the return type
Function PerformCalc() As Long End Function
You can see it is simple how you declare a variable. You can return any type you can declare as a variable including objects and collections.
A Quick Comparison
Sub:
- Cannot return a value.
- Can be called from VBAButtonEvent etc.
Function
- Can return a value but doesn’t have to.
- Can be called it from VBAButtonEvent etc. but it won’t appear in the list of Macros. You must type it in.
- If the function is public, will appear in the worksheet function list for the current workbook.
Note 1: You can use “Option Private Module” to hide subs in the current module. This means that subs won’t be visible to other projects and applications. They also won’t appear in a list of subs when you bring up the Macro window on the developer tab.
Note 2:We can use the word procedure to refer to a function or sub
Calling a Sub or Function
When people are new to VBA they tend to put all the code in one sub. This is not a good way to write your code.
It is better to break your code into multiple procedures. We can run one procedure from another.
Here is an example:
' https://excelmacromastery.com/ Sub Main() ' call each sub to perform a task CopyData AddFormulas FormatData End Sub Sub CopyData() ' Add code here End Sub Sub AddFormulas() ' Add code here End Sub Sub FormatData() ' Add code here End Sub
You can see that in the Main sub, we have added the name of three subs. When VBA reaches a line containing a procedure name, it will run the code in this procedure.
We refer to this as calling a procedure e.g. We are calling the CopyData sub from the Main sub.
There is actually a Call keyword in VBA. We can use it like this:
' https://excelmacromastery.com/ Sub Main() ' call each sub to perform a task Call CopyData Call AddFormulas Call FormatData End Sub
Using the Call keyword is optional. There is no real need to use it unless you are new to VBA and you feel it makes your code more readable.
If you are passing arguments using Call then you must use parentheses around them.
For example:
' https://excelmacromastery.com/ Sub Main() ' If call is not used then no parentheses AddValues 2, 4 ' call requires parentheses for arguments Call AddValues(2, 4) End Sub Sub AddValues(x As Long, y As Long) End Sub
How to Return Values From a Function
To return a value from a function you assign the value to the name of the Function. The following example demonstrates this:
' https://excelmacromastery.com/ Function GetAmount() As Long ' Returns 55 GetAmount = 55 End Function Function GetName() As String ' Returns John GetName = "John" End Function
When you return a value from a function you will obviously need to receive it in the function/sub that called it. You do this by assigning the function call to a variable. The following example shows this:
' https://excelmacromastery.com/ Sub WriteValues() Dim Amount As Long ' Get value from GetAmount function Amount = GetAmount End Sub Function GetAmount() As Long GetAmount = 55 End Function
You can easily test your return value using by using the Debug.Print function. This will write values to the Immediate Window (View->Immediate window from the menu or press Ctrl + G).
' https://excelmacromastery.com/ Sub WriteValues() ' Print return value to Immediate Window Debug.Print GetAmount End Sub Function GetAmount() As Long GetAmount = 55 End Function
Using Parameters and Arguments
We use parameters so that we can pass values from one sub/function to another.
The terms parameters and arguments are often confused:
- A parameter is the variable in the sub/function declaration.
- An argument is the value that you pass to the parameter.
' https://excelmacromastery.com/ Sub UsingArgs() ' The argument is 56 CalcValue 56 ' The argument is 34 CalcValue 34 End Sub ' The parameter is amount Sub CalcValue(ByVal amount As Long) End Sub
Here are some important points about parameters:
- We can have multiple parameters.
- A parameter is passed using either ByRef or ByVal. The default is ByRef.
- We can make a parameter optional for the user.
- We cannot use the New keyword in a parameter declaration.
- If no variable type is used then the parameter will be a variant by default.
The Format of Parameters
Subs and function use parameters in the same way.
The format of the parameter statement is as follows:
' All variables except arrays [ByRef/ByVal] As [Variable Type] ' Optional parameter - can only be a basic type [Optional] [ByRef/ByVal] [Variable name] As <[Variable Type] = ' Arrays [ByRef][array name]() As [Variable Type]
Here are some examples of the declaring different types of parameters:
' https://excelmacromastery.com/ ' Basic types Sub UseParams1(count As Long) End Sub Sub UseParams2(name As String) End Sub Sub UseParams3(amount As Currency) End Sub ' Collection Sub UseParamsColl(coll As Collection) End Sub ' Class module object Sub UseParamsClass(o As Class1) End Sub ' Variant ' If no type is give then it is automatically a variant Sub UseParamsVariant(value) End Sub Sub UseParamsVariant2(value As Variant) End Sub Sub UseParamsArray(arr() As String) End Sub
You can see that declaring parameters looks similar to using the Dim statement to declare variables.
Multiple Parameters
We can use multiple parameters in our sub/functions. This can make the line very long
Sub LongLine(ByVal count As Long, Optional amount As Currency = 56.77, Optional name As String = "John")
We can split up a line of code using the underscore (_) character. This makes our code more readable
Sub LongLine(ByVal count As Long _ , Optional amount As Currency = 56.77 _ , Optional name As String = "John")
Parameters With a Return Value
This error causes a lot of frustration with new users of VBA.
If you are returning a value from a function then it must have parentheses around the arguments.
The code below will give the “Expected: end of statement” syntax error.
' https://excelmacromastery.com/ Sub UseFunction() Dim result As Long result = GetValue 24.99 End Sub Function GetValue(amount As Currency) As Long GetValue = amount * 100 End Function
We have to write it like this
result = GetValue (24.99)
ByRef and ByVal
Every parameter is either ByRef or ByVal. If no type is specified then it is ByRef by default
' https://excelmacromastery.com/ ' Pass by value Sub WriteValue1(ByVal x As Long) End Sub ' Pass by reference Sub WriteValue2(ByRef x As Long) End Sub ' No type used so it is ByRef Sub WriteValue3(x As Long) End Sub
If you don’t specify the type then ByRef is the type as you can see in the third sub of the example.
The different between these types is:
ByVal – Creates a copy of the variable you pass.
This means if you change the value of the parameter it will not be changed when you return to the calling sub/function
ByRef – Creates a reference of the variable you pass.
This means if you change the value of the parameter variable it will be changed when you return to the calling sub/function.
The following code example shows this:
' https://excelmacromastery.com/ Sub Test() Dim x As Long ' Pass by value - x will not change x = 1 Debug.Print "x before ByVal is"; x SubByVal x Debug.Print "x after ByVal is"; x ' Pass by reference - x will change x = 1 Debug.Print "x before ByRef is"; x SubByRef x Debug.Print "x after ByRef is"; x End Sub Sub SubByVal(ByVal x As Long) ' x WILL NOT change outside as passed ByVal x = 99 End Sub Sub SubByRef(ByRef x As Long) ' x WILL change outside as passed ByRef x = 99 End Sub
The result of this is:
x before ByVal is 1
x after ByVal is 1
x before ByRef is 1
x after ByRef is 99
You should avoid passing basic variable types using ByRef. There are two main reasons for this:
- The person passing a value may not expect it to change and this can lead to bugs that are difficult to detect.
- Using parentheses when calling prevents ByRef working – see next sub section
A Little-Known Pitfall of ByRef
There is one thing you must be careful of when using ByRef with parameters. If you use parentheses then the sub/function cannot change the variable you pass even if it is passed as ByRef.
In the following example, we call the sub first without parentheses and then with parentheses. This causes the code to behave differently.
For example
' https://excelmacromastery.com/ Sub Test() Dim x As Long ' Call using without Parentheses - x will change x = 1 Debug.Print "x before (no parentheses): "; x SubByRef x Debug.Print "x after (no parentheses): "; x ' Call using with Parentheses - x will not change x = 1 Debug.Print "x before (with parentheses): "; x SubByRef (x) Debug.Print "x after (with parentheses): "; x End Sub Sub SubByRef(ByRef x As Long) x = 99 End Sub
If you change the sub in the above example to a function, you will see the same behaviour occurs.
However, if you return a value from the function then ByRef will work as normal as the code below shows:
' https://excelmacromastery.com/ Sub TestFunc() Dim x As Long, ret As Long ' Call using with Parentheses - x will not change x = 1 Debug.Print "x before (with parentheses): "; x FuncByRef (x) Debug.Print "x after (with parentheses): "; x ' Call using with Parentheses and return - x will change x = 1 Debug.Print "x before (with parentheses): "; x ret = FuncByRef(x) Debug.Print "x after (with parentheses): "; x End Sub Function FuncByRef(ByRef x As Long) x = 99 End Function
As I said in the last section you should avoid passing a variable using ByRef and instead use ByVal.
This means
- The variable you pass will not be accidentally changed.
- Using parentheses will not affect the behaviour.
ByRef and ByVal with Objects
When we use ByRef or ByVal with an object, it only affects the variable. It does not affect the actual object.
If we look at the example below:
' https://excelmacromastery.com/ Sub UseObject() Dim coll As New Collection coll.Add "Apple" ' After this coll with still reference the original CollByVal coll ' After this coll with reference the new collection CollByRef coll End Sub Sub CollByVal(ByVal coll As Collection) ' Original coll will still reference the original Set coll = New Collection coll.Add "ByVal" End Sub Sub CollByRef(ByRef coll As Collection) ' Original coll will reference the new collection Set coll = New Collection coll.Add "ByRef" End Sub
When we pass the coll variable using ByVal, a copy of the variable is created. We can assign anything to this variable and it will not affect the original one.
When we pass the coll variable using ByRef, we are using the original variable. If we assign something else to this variable then the original variable will also be assigned to something else.
You can see find out more about this here.
Optional Parameters
Sometimes we have a parameter that will often be the same value each time the code runs. We can make this parameter Optional which means that we give it a default value.
It is then optional for the caller to provide an argument. If they don’t provide a value then the default value is used.
In the example below, we have the report name as the optional parameter:
Sub CreateReport(Optional reportName As String = "Daily Report") End Sub
If an argument is not provided then name will contain the “Daily Report” text
' https://excelmacromastery.com/ Sub Main() ' Name will be "Daily Report" CreateReport ' Name will be "Weekly Report" CreateReport "Weekly Report" End Sub
The Optional parameter cannot come before a normal parameter. If you do this you will get an Expected: Optional error.
When a sub/function has optional parameters they will be displayed in square parentheses by the Intellisense.
In the screenshot below you can see that the name parameter is in square parentheses.
A sub/function can have multiple optional parameters. You may want to provide arguments to only some of the parameters.
There are two ways to do this:
If you don’t want to provide an argument then leave it blank.
A better way is to use the parameter name and the “:=” operator to specify the parameter and its’ value.
The examples below show both methods:
' https://excelmacromastery.com/ Sub Multi(marks As Long _ , Optional count As Long = 1 _ , Optional amount As Currency = 99.99 _ , Optional version As String = "A") Debug.Print marks, count, amount, version End Sub Sub UseBlanks() ' marks and count Multi 6, 5 ' marks and amount Multi 6, , 89.99 ' marks and version Multi 6, , , "B" ' marks,count and version Multi 6, , , "F" End Sub Sub UseName() ' marks and count Multi 12, count:=5 ' marks and amount Multi 12, amount:=89.99 ' marks and version Multi 12, version:="B" ' marks,count and version Multi 12, count:=6, version:="F" End Sub
Using the name of the parameter is the best way. It makes the code more readable and it means you won’t have error by mistakenly adding extra commas.
wk.SaveAs "C:Docsdata.xlsx", , , , , , xlShared wk.SaveAs "C:Docsdata.xlsx", AccessMode:=xlShared
IsMissing Function
We can use the IsMissing function to check if an Optional Parameter was supplied.
Normally we check against the default value but in certain cases we may not have a default.
We use IsMissing with Variant parameters because it will not work with basic types like Long and Double.
' https://excelmacromastery.com/ Sub test() ' Prints "Parameter not missing" CalcValues 6 ' Prints "Parameter missing" CalcValues End Sub Sub CalcValues(Optional x) ' Check for the parameter If IsMissing(x) Then Debug.Print "Parameter missing" Else Debug.Print "Parameter Not missing" End If End Sub
Custom Function vs Worksheet Function
When you create a function it appears in the function list for that workbook.
Have a look at the function in the next example.
Public Function MyNewFunction() MyNewFunction = 99 End Function
If you add this to a workbook then the function will appear in the function list. Type “=My” into the function box and the function will appear as shown in the following screenshot.
If you use this function in a cell you will get the result 99 in the cell as that is what the function returns.
Conclusion
The main points of this post are:
- Subs and macros are essentially the same thing in VBA.
- Functions return values but subs do not.
- Functions appear in the workbook function list for the current workbook.
- ByRef allows the function or sub to change the original argument.
- If you call a function sub with parentheses then ByRef will not work.
- Don’t use parentheses on sub arguments or function arguments when not returning a value.
- Use parentheses on function arguments when returning a value.
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Содержание
- Оператор Function
- Синтаксис
- Замечания
- Пример
- См. также
- Поддержка и обратная связь
- Function statement
- Syntax
- Remarks
- Example
- See also
- Support and feedback
Оператор Function
Объявляет имя, аргументы и код, формирующий текст процедурыFunction.
Синтаксис
[Общедоступная | Частная | Друг] [ Static ] Имяфункции [ ( arglist ) ] [ Astype ]
[ операторы ]
[ name=expression ]
[ Exit Function ]
[ операторы ]
[ name=expression ]
End Function
Синтаксис оператора Function содержит такие части:
Part | Описание |
---|---|
Public | Необязательный параметр. Указывает на то, что процедура Function доступна для всех других процедур во всех модулях. При использовании в модуле, который содержит Option Private, процедура недоступна вне проекта. |
Private | Необязательный параметр. Указывает на то, что процедура Function доступна только для других процедур в том модуле, в котором была объявлена. |
Friend | Необязательный параметр. Используется только в модуле класса. Указывает на то, что процедура Function видима повсюду в проекте, но невидима для контроллера экземпляра объекта. |
Static | Необязательный параметр. Указывает на то, что локальные переменные процедуры Function сохраняются между вызовами. Атрибут Static не влияет на переменные, которые были объявлены вне Function, даже если они используются в процедуре. |
name | Обязательно. Название Function; соответствует стандарту соглашений об именовании переменных. |
arglist | Необязательный параметр. Список переменных, представляющих аргументы, которые передаются в процедуру Function при вызове. В качестве разделителя переменных используется запятая. |
type | Необязательный параметр. Тип данных значения, возвращаемого процедурой Function ; Может быть Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (в настоящее время не поддерживается), Date, String (кроме фиксированной длины), Object, Variant или любого определяемого пользователем типа. |
Операторы | Необязательный параметр. Любая группа операторов, которая будет выполняться в процедуре Function. |
выражение | Необязательный параметр. Возвращаемое значение Function. |
Аргумент arglist имеет следующий синтаксис и элементы:
[ Необязательно ] [ ByVal | ByRef ] [ ParamArray ] varname [ ( ) ] [ Astype ] [ =defaultvalue ]
Part | Описание |
---|---|
Необязательное | Необязательный параметр. Указывает, что аргумент не является обязательным. Если используется, все последующие аргументы в списке ресурсов также должны быть необязательными и объявляться с помощью ключевого слова Optional . Optional не может использоваться для каких-либо аргументов, если используется ParamArray. |
ByVal | Необязательный параметр. Указывает, что аргумент передается значением. |
ByRef | Необязательный параметр. Указывает, что аргумент передается по ссылке. ByRef является значением по умолчанию в Visual Basic. |
ParamArray | Необязательный параметр. Используется как последний аргумент в arglist, чтобы указать, что последний аргумент является массивом Optional элементов Variant. Ключевое слово ParamArray позволяет предоставлять произвольное число аргументов. Не может использоваться с аргументами ByVal, ByRef или Optional. |
варнаме | Обязательно. Имя переменной, представляющее аргумент; соответствует стандарту соглашений об именовании переменных. |
type | Необязательный параметр. Тип данных аргумента, передаваемого процедуре; Могут быть byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (в настоящее время не поддерживается) Date, String (только переменная длина), Object, Variant или определенный тип объекта. Если параметр объявлен без ключевого слова Optional, можно также указать тип, определяемый пользователем. |
Defaultvalue | Необязательный параметр. Любая константа или константное выражение. Действительно только для параметров Optional. Если типом является Object, явным значением по умолчанию может быть только Nothing. |
Замечания
Если явно не указано с помощью public, private или Friend, процедуры функций по умолчанию являются общедоступными.
Если static не используется, значение локальных переменных не сохраняется между вызовами.
Ключевое слово Friend может использоваться только в модулях классов. Однако доступ к процедурам Friend может осуществляться в любом модуле проекта. Процедура Friend не отображается в библиотеке типов родительского класса, а также не может быть связана с опозданием.
Процедуры Function могут быть рекурсивными, то есть они могут вызывать сами себя для выполнения поставленной задачи. Однако рекурсия может стать причиной переполнения стека. Ключевое слово Static обычно не используется с рекурсивными процедурами Function.
Весь выполняемый код должен быть в процедурах. Невозможно определить процедуру Function внутри другой процедуры Function, Sub или Property .
Оператор Exit Function приводит к немедленному выходу из процедуры Function . Выполнение программы продолжается с оператором, следующим за оператором, который вызвал процедуру Function. В любом месте процедуры Function может появится любое количество операторов Exit Function.
Как и Sub, Function является отдельной процедурой, которая может содержать аргументы, выполнять наборы операторов и изменять значения их аргументов. Однако в отличие от Sub, процедуру Function можно использовать справа от выражения, как и при использовании любой встроенной функции, например Sqr, Cos или Chr, если необходимо использовать значение, возвращенное функцией.
Вы вызываете процедуру Function с помощью имени функции, за которой следует список аргументов в скобках в выражении. Дополнительные сведения о вызове процедур функции см. в инструкции Call.
Чтобы вернуть значение функции, присвойте значение названию функции. В любом месте процедуры может появится любое количество таких назначений. Если параметру name не присвоено значение, процедура вернет значение по умолчанию: числовая функция вернет 0, строковая функция вернет строку нулевой длины («»), а функция Variant вернет значение Empty. Функция, которая возвращает объектную ссылку, возвращает значение Nothing, если для параметра name не присвоено ни одной объектной ссылки (с помощью Set) в Function.
В следующем примере показано, как присвоить функции возвращаемое значение. В этом случае значение False присваивается названию, чтобы указать, что некоторые значения не были найдены.
Переменные, которые используются в процедурах Function, делятся на две категории: те, которые явно объявлены в процедуре, и те, которые нет.
Переменные, которые явно объявлены в процедуре (с помощью оператора Dim или его эквивалента), всегда являются локальными в процедуре. Переменные, которые используются, но не были явно объявлены в процедуре, также являются локальными, если они не были объявлены на более высоком уровне вне процедуры.
В процедуре может использоваться переменная, которая не была явно объявлена в процедуре, но если какой-либо элемент, который был определен на уровне модуля, имеет такое же название, может возникнуть конфликт. Если ваша процедура ссылается на необъявленную переменную, которая называется так же, как и другая процедура, константа или переменная, система посчитает, что ваша процедура ссылается на это название на уровне модуля. Следует явно объявлять переменные, чтобы избежать таких конфликтов. Используйте оператор Option Explicit для принудительного объявления переменных.
Visual Basic может менять порядок арифметических выражений для повышения внутренней эффективности. Избегайте использования процедуры Function в арифметических выражениях, если функция меняет значение переменных в одном выражении. Дополнительные сведения об арифметических операторах см. в разделе Операторы.
Пример
В этом примере оператор Function используется для объявления названия, аргументов и кода, которые составляют основной текст процедуры Function. В последнем примере используются фиксированные инициализированные аргументы Optional.
Использование ключевых слов ParamArray позволяет функции принимать переменное число аргументов. В следующем определении он передается по значению.
Необязательные аргументы могут иметь значения по умолчанию и типы, отличные от Variant.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
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.
Источник