Функции visual basic для excel

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

Excel VBA Functions

We have seen that we can use the worksheet functions in VBA, i.e., the Excel worksheet functions in VBA coding using the Application.Worksheet method. But how do we use a function of VBA in Excel well? Such functions are called user-defined functions. When a user creates a function in VBA, we can use it in an Excel worksheet.

Although we have many functions in Excel to manipulate the data, sometimes we need to have some customization in the tools to save time as we do some tasks repeatedly. For example, we have predefined functions in excel like SUM, COUNTIFThe COUNTIF function in Excel counts the number of cells within a range based on pre-defined criteria. It is used to count cells that include dates, numbers, or text. For example, COUNTIF(A1:A10,”Trump”) will count the number of cells within the range A1:A10 that contain the text “Trump”
read more
, SUMIFThe SUMIF Excel function calculates the sum of a range of cells based on given criteria. The criteria can include dates, numbers, and text. For example, the formula “=SUMIF(B1:B5, “<=12”)” adds the values in the cell range B1:B5, which are less than or equal to 12.
read more
, COUNTIFS,”COUNTIFSread more VLOOKUPThe VLOOKUP excel function searches for a particular value and returns a corresponding match based on a unique identifier. A unique identifier is uniquely associated with all the records of the database. For instance, employee ID, student roll number, customer contact number, seller email address, etc., are unique identifiers.
read more
, INDEX, MATCH in excelThe MATCH function looks for a specific value and returns its relative position in a given range of cells. The output is the first position found for the given value. Being a lookup and reference function, it works for both an exact and approximate match. For example, if the range A11:A15 consists of the numbers 2, 9, 8, 14, 32, the formula “MATCH(8,A11:A15,0)” returns 3. This is because the number 8 is at the third position.
read more
, etc., but we do some tasks daily for which a single command or function is not available in Excel. Using VBA, we can create the User Defined Functions (UDFUser Defined Function in VBA is a group of customized commands created to give out a certain result. It is a flexibility given to a user to design functions similar to those already provided in Excel.read more) custom function.

Table of contents
  • Excel VBA Functions
    • What do VBA Functions do?
    • How to Create Custom Functions using VBA?
      • Example
        • Step 1: Find Total Marks
        • Step 2: Create ResultOfStudent Function
        • Step 3: Apply ResultOfStudents Function to Get Result
        • Step 4: Create ‘GradeForStudent’ Function to get Grades
    • Recommended Articles

VBA Functions

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Functions (wallstreetmojo.com)

What do VBA Functions do?

  • They carry out certain calculations; and
  • Return a value

In VBA, while defining the function, we use the following syntax to specify the parameters and their data type.

Data type here is the type of dataData type is the core character of any variable, it represents what is the type of value we can store in the variable and what is the limit or the range of values which can be stored in the variable, data types are built-in VBA and user or developer needs to be aware which type of value can be stored in which data type. Data types assign to variables tells the compiler storage size of the variable.read more the variable will hold. It can hold any value (data type or class object).

Marks as Integer

We can connect the object with its property or method using the period or dot (.) symbol.

How to Create Custom Functions using VBA?

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

Example

Suppose we have the following data from a school where we need to find the total marks scored by the student, result, and grade.

VBA Function Example 1

To sum up, the marks scored by an individual student in all subjects, we have an inbuilt function, SUM. But, determining the grade and result based on the criteria set out by the school is not available in Excel by default.

It is the reason why we need to create user-defined functions.

Step 1: Find Total Marks

First, we will find the total marks using the SUM function in excelThe SUM function in excel adds the numerical values in a range of cells. Being categorized under the Math and Trigonometry function, it is entered by typing “=SUM” followed by the values to be summed. The values supplied to the function can be numbers, cell references or ranges.read more.

VBA Function Example 1-1

Then, press the “Enter” key to get the result.

VBA Function Example 1-2

Drag the formula to the rest of the cells.

VBA Function Example 1-3

Now, to find out the result (passed, failed, or essential repeat), the criteria set by the school is that.

  • Suppose a student has scored more than or equal to 200 as total marks out of 500. In addition, suppose they have also not failed in any subject (scored more than 32 in each subject), a student is passed.
  • If the student scored more than or equal to 200 but failed in 1 or 2 subjects, then a student will get “Essential Repeat” in those subjects.
  • If the student has scored either less than 200 or fails in 3 or more subjects, then the student failed.
Step 2: Create ResultOfStudent Function

To create a function named ‘ResultOfStudent,’ we need to open “Visual Basic Editor” by using any of the methods below:

  • Using the Developer tab excel.Enabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more

VBA Function Example 1-4

If the Developer tab is not available in MS Excel, then we can get that by using the following steps:

  • Right-click anywhere on the ribbon. Then, choose to Customize the Ribbon in excelRibbons in Excel 2016 are designed to help you easily locate the command you want to use. Ribbons are organized into logical groups called Tabs, each of which has its own set of functions.read more.

VBA Function Example 1-5

When we choose this command, the “Excel Options” dialog box opens.

  • We need to check the box for “Developer” to get the tab.

VBA Function Example 1-6

  • Using the shortcut key, Alt+F11.

VBA Function Shortcut Key

  • When we open the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more, we need to insert the module by going to the Insert menu and choosing a module.

VBA Function Example 1-7

  • We need to paste the following code into the module.
Function ResultOfStudents(Marks As Range) As String

Dim mycell As Range
Dim Total As Integer
Dim CountOfFailedSubject As Integer

For Each mycell In Marks
Total = Total + mycell.Value

If mycell.Value < 33 Then
CountOfFailedSubject = CountOfFailedSubject + 1
End If

Next mycell
If Total >= 200 And CountOfFailedSubject <= 2 And CountOfFailedSubject > 0 Then
ResultOfStudents = "Essential Repeat"

ElseIf Total >= 200 And CountOfFailedSubject = 0 Then
ResultOfStudents = "Passed"

Else
ResultOfStudents = "Failed"
End If

End Function

VBA Function Example 1-8

The above function returns the result for a student.

We need to understand how this code is working.

The first statement, ‘Function ResultOfStudents(Marks As Range) As String,’ declares a function named ‘ResultOfStudents’ that will accept a range as input for marks and return the result as a string.

Dim mycell As Range
Dim Total As Integer
Dim CountOfFailedSubject As Integer

These three statements declare variables, i.e.,

  • ‘myCell’ as a Range,
  • ‘Total’ as Integer (to store total marks scored by a student),
  • ‘CountOfFailedSubject’ is an Integer (to store the number of subjects a student has failed).
For Each mycell In Marks
Total = Total + mycell.Value

If mycell.Value < 33 Then
CountOfFailedSubject = CountOfFailedSubject + 1
End If

Next mycell

This code checks for every cell in the ‘Marks’ range. It adds the value of every cell in the ‘Total’ variable. If the cell’s value is less than 33, add 1 to the ‘CountOfFailedSubject’ variable.

If Total >= 200 And CountOfFailedSubject <= 2 And CountOfFailedSubject > 0 Then
ResultOfStudents = "Essential Repeat"

ElseIf Total >= 200 And CountOfFailedSubject = 0 Then
ResultOfStudents = "Passed"

Else
ResultOfStudents = "Failed"
End If

This code checks the value of ‘Total’ and ‘CountOfFailedSubject’ and passes the Essential Report,’ ‘Passed,’ or ‘Failed’ to the ‘ResultOfStudents.’

Step 3: Apply ResultOfStudents Function to Get Result

ResultOfStudents function takes marks, i.e., selecting 5 marks scored by the student.

VBA Function Example 1-10

Now, select the range of cells, B2: F2.

Example 1-11

Drag the formula to the rest of the cells.

Example 1-13

Step 4: Create ‘GradeForStudent’ Function to get Grades

Now to find out the grade for the student, we will create one more function named ‘GradeForStudent.’

The code would be:

Function GradeForStudent(TotalMarks As Integer, Result As String) As String

If TotalMarks > 440 And TotalMarks <= 500 And ((Result = "Passed" Or Result = "Essential Repeat") 
Or Result = "Essential Repeat") Then GradeForStudent = "A"

ElseIf TotalMarks > 380 And TotalMarks <= 440 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "B"

ElseIf TotalMarks > 320 And TotalMarks <= 380 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "C"

ElseIf TotalMarks > 260 And TotalMarks <= 320 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "D"

ElseIf TotalMarks >= 200 And TotalMarks <= 260 And (Result = "Passed" Or Result = "Essential Repeat") Then
GradeForStudent = "E"

ElseIf TotalMarks < 200 Or Result = "Failed" Then
GradeForStudent = "F"

End If

End Function

This function assigns a ‘Grade’ to the student based on the ‘Total Marks’ and ‘Result.’

VBA Function Example 1-9

We need to write the formula and open the brackets in cell H2. Press Ctrl+Shift+A to find out the arguments.

VBA Function Shortcut arguments

The GradeForStudent function takes Total marks (sum of marks) and the result of the student as an argument to calculate the grade.

Example 1-14

Now, select the individual cells, G2 and H2.

Example 1-15

Now, we need to press Ctrl+D after selecting the cells to copy down the formulas.

Example 1-16

We can highlight the values of less than 33 with the red background color to find out the subjects in which the student failed.

Example 1-17

Recommended Articles

This article is a guide to VBA Functions. Here, we discuss creating custom functions using VBA code, practical examples, and a downloadable Excel template. You may learn more about VBA from the following articles:-

  • VBA IIFThe «VBA IIF» condition evaluates the supplied expression or logical test and returns TRUE or FALSE as a result.read more
  • SUMIF With VLOOKUPSUMIF is used to sum cells based on some condition, which takes arguments of range, criteria, or condition, and cells to sum. When there is a large amount of data available in multiple columns, we can use VLOOKUP as the criteria.read more
  • Excel SUMIF Between Two DatesWhen we wish to work with data that has serial numbers with different dates and the condition to sum the values is based between two dates, we use Sumif between two dates. read more
  • Excel VBA Delete RowIn VBA, to delete the command and to delete any rows together, the trick is that we give a single row reference if we need to delete a single row. However, for the multiple columns, we can provide numerous row references.read more

Best Landing PagesYou can use Visual Basic for Applications to write macros in Excel, or other Microsoft Office apps. Macros are programs that can be used to perform an action repetitively. For example, you can write a macro to get the data from two cells in two distinct columns, add it and then return the output to the user. Now, whenever you want to add the data in two different columns, you can call the macro that you wrote earlier instead of typing a formula in the formula bar each time. You can see why macros are useful- and also why it’s a good idea to learn how to create them. You can learn more about VBA macros in this introductory course.

In this tutorial, we’ll take a look at a couple of the most-used functions in VBA. We’ll also teach you how to write a basic function of your own. VBA has many inbuilt functions that can help you perform a wide range of tasks. These inbuilt functions are more than enough for your everyday needs. Some of these functions include:

  • Date and Time functions: You can use date and time functions to insert the current system date and time. They let you handle and manipulate time values, in general.A few basic date and time functions are: DATE, MINUTE, MONTH and YEAR.
  • Finance-Related functions: Excel is a spreadsheet program. It incorporates extensive support for finance related activities. Finance-related functions can be used to handle money, in general. Some of the basic functions include: IPMT, PV and SYD.
  • Directory functions: Directory functions can be used to link files on the computer with the spreadsheet. Some of the common directory functions include: CHDRIVE, DIR and GETATTR.
  • Logical functions: Logical functions can be used to execute code if a certain statement is satisfied. The ones most used are: AND, IF THEN ELSE and OR.
  • Mathematical functions: You can use mathematical functions to manipulate numbers. The most common arithmetic functions include: INT, LOG and VAL.
  • String functions: String functions let you work with strings. Some of the common ones include: RIGHT, REPLACE, LEN and STR.

If you’re going to be using VBA, you need to have a working familiarity with most of these functions. You can learn more about these VBA Macros and functions with this course.

MsgBox function in VBA

The MsgBox function is one of the most used functions in VBA. The MsgBox function creates a dialog box that can be used to display a message or return a value to the user. The dialog box has, by default, an ok button and a cancel button (just like a typical dialog box you find in Windows). The syntax for the message box function is as follows:

     MsgBox(prompt[,buttons][,title][.helpfile, context])

The prompt parameter is essential. It is the message the MsgBox will display to the user. The other three parameters are optional. The title parameter is the title of the message box. If you don’t want to specify the title, the title of the application is used as default. The buttons parameter is used to select the buttons you want your message box to display. By default, the value is taken as 0 (the OK button). If you wanted to display the Yes, No and Cancel buttons, you can set the button value to 3.

Now let’s write a simple message box function that displays a message to the user. We will need to place a command button on our spreadsheet and then edit the source code, like this:

Private Sub CommandButton1_Click()
MsgBox ("This is a Message Box")
End Sub

When the user clicks on this command button, the message box will pop up:

VBAFunction1

You will find the command button in the developer tab, in the insert option. You may have to customize your ribbon to add the developer tab (it’s disabled by default). If you need help accessing the VBA screen, we recommend you take this course on using Excel with VBA.

The If Then Else function

Now let’s take a look at another easy function in VBA- the If Then Else function. You can execute two separate bodies of code with the help of this conditional statement. Depending on the condition, one of the two bodies of code you specified will be executed.

The syntax for the If Then Else function is as follows:

If your_condition Then
code1_to_be_executed
Else
code2_to_be_executed

Let’s write a simple program to help you understand it better. Much like the example above, we’ll first place a command button on our spreadsheet and then edit the source code:

Private Sub CommandButton1_Click()
Dim a, b, c As Integer
a = 1
b = 2
c = a + b
If c < 4 Then
MsgBox ("c is less than 4")
Else
MsgBox ("c is greater than 4")
End Sub

Explanation: First, we’ve taken three variables a, b and c and set them as integer data types. We’ve specified the values of a and b. Finally, c holds the sum of the values of a and b. Our conditional statement asksVBA to print “c is less than 4” in a MsgBox if the value of c is less than 4. Otherwise, it must print “c is greater than 4”. Of course, this is a contrived example. In a real VBA program, the values of a and b might be taken from two cells in your columns. The code to be executed will also be different. You can try out some real world examples with MrExcel in this awesome VBA course.

User Defined Functions in VBA

You can write user defined functions in VBA that you can call from the formula bar. These functions will usually take values from the cells in your spreadsheet, perform operations on them and return a value. For example, you can write a simple function to calculate the area of a square:

Function AreaSq(LengthofSide As Double) As Double
     AreaSq = LengthofSide*LengthofSide
End Function

Explanation: Here, we’ve declared AreaSq and LengthofSide as Double data type (able to hold decimal values). Now, you navigate to a blank cell in the worksheet and type in the formula bar:

=AreaSq (C1)

Now, assuming there was a number value in cell C1, your blank cell will now hold the area of the square.

Code Module

Please note that you must save the function in a module before it can be called in your spreadsheet. First, navigate to the Visual Basic screen and click on the Insert menu and then choose the Module option. A blank project screen will show up. You can type your code here. A module can hold many functions – you don’t have to create a new module every time you write a new function.

The module that you create will be attached to the current workbook. It’s possible to use functions attached to other workbooks if you specify the workbook name before using the function. For example, if the AreaSq function was located in a workbook called “Book2”, you can use it by typing the following in the formula bar:

= ‘Book2.xls’ !AreaSq(C1)

You can also define a function as an Add-In. This way, you don’t need to specify the name of the workbook before you use it.

We’ve tried to walk you through the most important VBA functions. You can learn many more useful ones, and even how to create your own complex functions with this Ultimate VBA course.

Создание пользовательской функции в VBA Excel, ее синтаксис и компоненты. Описание пользовательской функции и ее аргументов. Метод Application.MacroOptions.

Пользовательская функция — это процедура VBA, которая производит заданные вычисления и возвращает полученный результат. Используется для вставки в ячейки рабочего листа Excel или для вызова из других процедур.

Объявление пользовательской функции

Синтаксис функции

[Static] Function Имя ([СписокАргументов])[As ТипДанных]

[Операторы]

[Имя = выражение]

[Exit Function]

[Операторы]

[Имя = выражение]

End Function

Компоненты функции

  • Static — необязательное ключевое слово, указывающее на то, что значения переменных, объявленных в функции, сохраняются между ее вызовами.
  • Имя — обязательный компонент, имя пользовательской функции.
  • СписокАргументов — необязательный компонент, одна или более переменных, представляющих аргументы, которые передаются в функцию. Аргументы заключаются в скобки и разделяются между собой запятыми.
  • Операторы — необязательный компонент, блок операторов (инструкций).
  • Имя = выражение — необязательный* компонент, присвоение имени функции значения выражения или переменной. Обычно, значение присваивается функции непосредственно перед выходом из нее.
  • Exit Function — необязательный компонент, принудительный выход из функции, если ей уже присвоено окончательное значение.

*Один из компонентов Имя = выражение следует считать обязательным, так как если не присвоить функции значения, смысл ее использования теряется.

Видимость функции

Видимость пользовательской функции определяется необязательными ключевыми словами Public и Private, которые могут быть указаны перед оператором Function (или Static, в случае его использования).

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

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

Если ключевое слово Public или Private не указано, функция считается по умолчанию объявленной, как Public.

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

Пример пользовательской функции

Для примера мы рассмотрим простейшую пользовательскую функцию, которой в следующем параграфе добавим описание. Называется функция «Деление», объявлена с типом данных Variant, так как ее возвращаемое значение может быть и числом, и текстом. Аргументы функции — Делимое и Делитель — тоже объявлены как Variant, так как в ячейках Excel могут быть числовые значения разных типов, и функция IsNumeric тоже проверяет разные типы данных и требует, чтобы ее аргументы были объявлены как Variant.

Function Деление(Делимое As Variant, Делитель As Variant) As Variant

  If IsNumeric(Делимое) = False Or IsNumeric(Делитель) = False Then

    Деление = «Ошибка: Делимое и Делитель должны быть числами!»

Exit Function

  ElseIf Делитель = 0 Then

    Деление = «Ошибка: деление на ноль!»

Exit Function

  Else

    Деление = Делимое / Делитель

  End If

End Function

Эта функция выполняет деление значений двух ячеек рабочего листа Excel. Перед делением проверяются два блока условий:

  • Если делимое или делитель не являются числом, функция возвращает значение: «Ошибка: Делимое и Делитель должны быть числами!», и производится принудительный выход из функции оператором Exit Function.
  • Если делитель равен нулю, функция возвращает значение: «Ошибка: деление на ноль!», и производится принудительный выход из функции оператором Exit Function.

Если проверяемые условия не выполняются (возвращают значение False) производится деление чисел и функция возвращает частное (результат деления).

Вы можете скопировать к себе в стандартный модуль эту функцию и она станет доступна в разделе «Определенные пользователем» Мастера функций. Попробуйте вставить функцию «Деление» в ячейку рабочего листа с помощью Мастера и поэкспериментируйте с ней.

Практического смысла функция «Деление» не имеет, но она хорошо демонстрирует как объявляются, создаются и работают пользовательские функции в VBA Excel. А еще она поможет продемонстрировать, как добавлять к функциям и аргументам описания. С полноценной пользовательской функцией вы можете ознакомиться здесь.

Добавление описания функции

В списке функций, выводимом Мастером, невозможно добавить или отредактировать их описание. Список макросов позволяет добавлять процедурам описание, но в нем нет функций. Проблема решается следующим образом:

  • Запустите Мастер функций, посмотрите, как отображается имя нужной функции и закройте его.
  • Откройте список макросов и в поле «Имя макроса» впишите имя пользовательской функции.
  • Нажмите кнопку «Параметры» и в открывшемся окне добавьте или отредактируйте описание.
  • Нажмите кнопку «OK», затем в окне списка макросов — «Отмена». Описание готово!

Добавление описания на примере функции «Деление»:

Добавление описания пользовательской функции в окне «Параметры макроса»

Добавление описания пользовательской функции

Описание функции «Деление» в диалоговом окне Мастера функций «Аргументы функции»:

Описание пользовательской функции в диалоговом окне «Аргументы функции»

Описание пользовательской функции в окне «Аргументы функции»

С помощью окна «Список макросов» можно добавить описание самой функции, а ее аргументам нельзя. Но это можно сделать, используя метод Application.MacroOptions.

Метод Application.MacroOptions

Метод Application.MacroOptions позволяет добавить пользовательской функции описание, назначить сочетание клавиш, указать категорию, добавить описания аргументов и добавить или изменить другие параметры. Давайте рассмотрим возможности этого метода, используемые чаще всего.

Пример кода с методом Application.MacroOptions:

Sub ИмяПодпрограммы()

  Application.MacroOptions _

    Macro:=«ИмяФункции», _

    Description:=«Описание функции», _

    Category:=«Название категории», _

    ArgumentDescriptions:=Array(«Описание 1», «Описание 2», «Описание 3», ...)

End Sub

  • ИмяПодпрограммы — любое уникальное имя, подходящее для наименования процедур.
  • ИмяФункции — имя функции, параметры которой добавляются или изменяются.
  • Описание функции — описание функции, которое добавляется или изменяется.
  • Название категории — название категории в которую будет помещена функция. Если параметр Category отсутствует, пользовательская функция будет записана в раздел по умолчанию — «Определенные пользователем». Если указанное Название категории соответствует одному из названий стандартного списка, функция будет записана в него. Если такого Названия категории нет в списке, будет создан новый раздел с этим названием и функция будет помещена в него.
  • «Описание 1», «Описание 2», «Описание 3», … — описания аргументов в том порядке, как они расположены в объявлении пользовательской функции.

Эта подпрограмма запускается один раз, после чего ее можно удалить или использовать как шаблон для корректировки параметров других пользовательских функций.

Сейчас с помощью метода Application.MacroOptions попробуем изменить описание пользовательской функции «Деление» и добавить описания аргументов.

Sub ИзменениеОписания()

  Application.MacroOptions _

    Macro:=«Деление», _

    Description:=«Описание функции Деление изменено методом Application.MacroOptions», _

    ArgumentDescriptions:=Array(«- любое числовое значение», «- числовое значение, кроме нуля»)

End Sub

После однократного запуска этой подпрограммы получаем следующий результат:

Новое описание пользовательской функции и ее второго аргумента

Новое описание пользовательской функции и ее второго аргумента

Метод Application.MacroOptions не работает в Личной книге макросов, но и здесь можно найти решение. Добавьте описания к пользовательским функциям и их аргументам в обычной книге Excel, затем экспортируйте модуль с функциями в любой каталог на жестком диске и оттуда импортируйте в Личную книгу макросов. Все описания сохранятся.

Понравилась статья? Поделить с друзьями:
  • Функции excel для работы с файлами
  • Функции vba для word
  • Функции excel для работы с матрицами
  • Функции vba excel что это
  • Функции excel для работы с массивами данных в excel