User defined functions for excel

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 More…Less

Although Excel includes a multitude of built-in worksheet functions, chances are it doesn’t have a function for every type of calculation you perform. The designers of Excel couldn’t possibly anticipate every user’s calculation needs. Instead, Excel provides you with the ability to create custom functions, which are explained in this article.

Custom functions, like macros, use the Visual Basic for Applications (VBA) programming language. They differ from macros in two significant ways. First, they use Function procedures instead of Sub procedures. That is, they start with a Function statement instead of a Sub statement and end with End Function instead of End Sub. Second, they perform calculations instead of taking actions. Certain kinds of statements, such as statements that select and format ranges, are excluded from custom functions. In this article, you’ll learn how to create and use custom functions. To create functions and macros, you work with the Visual Basic Editor (VBE), which opens in a new window separate from Excel.

Suppose your company offers a quantity discount of 10 percent on the sale of a product, provided the order is for more than 100 units. In the following paragraphs, we’ll demonstrate a function to calculate this discount.

The example below shows an order form that lists each item, quantity, price, discount (if any), and the resulting extended price.

Example order form without a custom function

To create a custom DISCOUNT function in this workbook, follow these steps:

  1. Press Alt+F11 to open the Visual Basic Editor (on the Mac, press FN+ALT+F11), and then click Insert > Module. A new module window appears on the right-hand side of the Visual Basic Editor.

  2. Copy and paste the following code to the new module.

    Function DISCOUNT(quantity, price)
       If quantity >=100 Then
         DISCOUNT = quantity * price * 0.1
       Else
         DISCOUNT = 0
       End If
     
     DISCOUNT = Application.Round(Discount, 2)
    End Function
    

Note: To make your code more readable, you can use the Tab key to indent lines. The indentation is for your benefit only, and is optional, as the code will run with or without it. After you type an indented line, the Visual Basic Editor assumes your next line will be similarly indented. To move out (that is, to the left) one tab character, press Shift+Tab.

Now you’re ready to use the new DISCOUNT function. Close the Visual Basic Editor, select cell G7, and type the following:

=DISCOUNT(D7,E7)

Excel calculates the 10 percent discount on 200 units at $47.50 per unit and returns $950.00.

In the first line of your VBA code, Function DISCOUNT(quantity, price), you indicated that the DISCOUNT function requires two arguments, quantity and price. When you call the function in a worksheet cell, you must include those two arguments. In the formula =DISCOUNT(D7,E7), D7 is the quantity argument, and E7 is the price argument. Now you can copy the DISCOUNT formula to G8:G13 to get the results shown below.

Let’s consider how Excel interprets this function procedure. When you press Enter, Excel looks for the name DISCOUNT in the current workbook and finds that it is a custom function in a VBA module. The argument names enclosed in parentheses, quantity and price, are placeholders for the values on which the calculation of the discount is based.

Example order form with a custom function

The If statement in the following block of code examines the quantity argument and determines whether the number of items sold is greater than or equal to 100:

If quantity >= 100 Then
 DISCOUNT = quantity * price * 0.1
Else
 DISCOUNT = 0
End If

If the number of items sold is greater than or equal to 100, VBA executes the following statement, which multiplies the quantity value by the price value and then multiplies the result by 0.1:

Discount = quantity * price * 0.1

The result is stored as the variable Discount. A VBA statement that stores a value in a variable is called an assignment statement, because it evaluates the expression on the right side of the equal sign and assigns the result to the variable name on the left. Because the variable Discount has the same name as the function procedure, the value stored in the variable is returned to the worksheet formula that called the DISCOUNT function.

If quantity is less than 100, VBA executes the following statement:

Discount = 0

Finally, the following statement rounds the value assigned to the Discount variable to two decimal places:

Discount = Application.Round(Discount, 2)

VBA has no ROUND function, but Excel does. Therefore, to use ROUND in this statement, you tell VBA to look for the Round method (function) in the Application object (Excel). You do that by adding the word Application before the word Round. Use this syntax whenever you need to access an Excel function from a VBA module.

A custom function must start with a Function statement and end with an End Function statement. In addition to the function name, the Function statement usually specifies one or more arguments. You can, however, create a function with no arguments. Excel includes several built-in functions—RAND and NOW, for example—that don’t use arguments.

Following the Function statement, a function procedure includes one or more VBA statements that make decisions and perform calculations using the arguments passed to the function. Finally, somewhere in the function procedure, you must include a statement that assigns a value to a variable with the same name as the function. This value is returned to the formula that calls the function.

The number of VBA keywords you can use in custom functions is smaller than the number you can use in macros. Custom functions are not allowed to do anything other than return a value to a formula in a worksheet, or to an expression used in another VBA macro or function. For example, custom functions cannot resize windows, edit a formula in a cell, or change the font, color, or pattern options for the text in a cell. If you include “action” code of this kind in a function procedure, the function returns the #VALUE! error.

The one action a function procedure can do (apart from performing calculations) is display a dialog box. You can use an InputBox statement in a custom function as a means of getting input from the user executing the function. You can use a MsgBox statement as a means of conveying information to the user. You can also use custom dialog boxes, or UserForms, but that’s a subject beyond the scope of this introduction.

Even simple macros and custom functions can be difficult to read. You can make them easier to understand by typing explanatory text in the form of comments. You add comments by preceding the explanatory text with an apostrophe. For example, the following example shows the DISCOUNT function with comments. Adding comments like these makes it easier for you or others to maintain your VBA code as time passes. If you need to make a change to the code in the future, you’ll have an easier time understanding what you did originally.

Example of a VBA function with Comments

An apostrophe tells Excel to ignore everything to the right on the same line, so you can create comments either on lines by themselves or on the right side of lines containing VBA code. You might begin a relatively long block of code with a comment that explains its overall purpose and then use inline comments to document individual statements.

Another way to document your macros and custom functions is to give them descriptive names. For example, rather than name a macro Labels, you could name it MonthLabels to describe more specifically the purpose the macro serves. Using descriptive names for macros and custom functions is especially helpful when you’ve created many procedures, particularly if you create procedures that have similar but not identical purposes.

How you document your macros and custom functions is a matter of personal preference. What’s important is to adopt some method of documentation, and use it consistently.

To use a custom function, the workbook containing the module in which you created the function must be open. If that workbook is not open, you get a #NAME? error when you try to use the function. If you reference the function in a different workbook, you must precede the function name with the name of the workbook in which the function resides. For example, if you create a function called DISCOUNT in a workbook called Personal.xlsb and you call that function from another workbook, you must type =personal.xlsb!discount(), not simply =discount().

You can save yourself some keystrokes (and possible typing errors) by selecting your custom functions from the Insert Function dialog box. Your custom functions appear in the User Defined category:

insert function dialog box

An easier way to make your custom functions available at all times is to store them in a separate workbook and then save that workbook as an add-in. You can then make the add-in available whenever you run Excel. Here’s how to do this:

  1. After you have created the functions you need, click File > Save As.

    In Excel 2007, click the Microsoft Office Button, and click Save As

  2. In the Save As dialog box, open the Save As Type drop-down list, and select Excel Add-In. Save the workbook under a recognizable name, such as MyFunctions, in the AddIns folder. The Save As dialog box will propose that folder, so all you need to do is accept the default location.

  3. After you have saved the workbook, click File > Excel Options.

    In Excel 2007, click the Microsoft Office Button, and click Excel Options.

  4. In the Excel Options dialog box, click the Add-Ins category.

  5. In the Manage drop-down list, select Excel Add-Ins. Then click the Go button.

  6. In the Add-Ins dialog box, select the check box beside the name you used to save your workbook, as shown below.

    add-ins dialog box

  1. After you have created the functions you need, click File > Save As.

  2. In the Save As dialog box, open the Save As Type drop-down list, and select Excel Add-In. Save the workbook under a recognizable name, such as MyFunctions.

  3. After you have saved the workbook, click Tools > Excel Add-Ins.

  4. In the Add-Ins dialog box, select the Browse button to find your add-in, click Open, then check the box beside your Add-In in the Add-Ins Available box.

After you follow these steps, your custom functions will be available each time you run Excel. If you want to add to your function library, return to the Visual Basic Editor. If you look in the Visual Basic Editor Project Explorer under a VBAProject heading, you will see a module named after your add-in file. Your add-in will have the extension .xlam.

named module in vbe

Double-clicking that module in the Project Explorer causes the Visual Basic Editor to display your function code. To add a new function, position your insertion point after the End Function statement that terminates the last function in the Code window, and begin typing. You can create as many functions as you need in this manner, and they will always be available in the User Defined category in the Insert Function dialog box.

This content was originally authored by Mark Dodge and Craig Stinson as part of their book Microsoft Office Excel 2007 Inside Out. It has since been updated to apply to newer versions of Excel as well.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Need more help?

Skip to content

Как создать пользовательскую функцию?

В решении многих задач обычные функции Excel не всегда могут помочь. Если существующих функций недостаточно, Excel позволяет добавить новые настраиваемые пользовательские функции (UDF). Они делают вашу работу легче.

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

  • Что такое пользовательская функция
  • Для чего ее используют?
  • Как создать пользовательскую функцию в VBA?
  • Как использовать пользовательскую функцию в формуле?
  • Какие бывают типы пользовательских функций

Что такое пользовательская функция в Excel?

На момент написания этой статьи Excel предлагает вам более 450 различных функций. С их помощью вы можете выполнять множество различных операций. Но разработчики Microsoft Excel не могли предвидеть все задачи, которые нам нужно решать. Думаю, что многие из вас встречались с этими проблемами:

  • не все данные могут быть обработаны стандартными функциями (например, даты до 1900 года).
  • формулы могут быть весьма длинными и сложными. Их невозможно запомнить, трудно понять и сложно изменить для решения новой задачи.
  • Не все задачи могут быть решены при помощи стандартных функций Excel (в частности, нельзя извлечь интернет-адрес из гиперссылки).
  • Невозможно автоматизировать часто повторяющиеся стандартные операции (импорт данных из бухгалтерской программы на лист Excel, форматирование дат и чисел, удаление лишних колонок).

Как можно решить эти проблемы?

  • Для очень сложных формул многие пользователи создают архив рабочих книг с примерами. Они копируют оттуда нужную формулу и применяют ее в своей таблице.
  • Создание макросов VBA.
  • Создание пользовательских функций при помощи редактора VBA.

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

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

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

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

Существует несколько способов создания собственных функций:

  • при помощи Visual Basic for Applications (VBA). Этот способ описывается в данной статье.
  • с использованием замечательной функции LAMBDA, которая появилась в Office365.
  • при помощи Office Scripts. На момент написания этой статьи они доступны в Excel Online в подписке на Office365.

Посмотрите на скриншот ниже, чтобы увидеть разницу между двумя способами извлечения чисел — с использованием формулы и пользовательской функции ExtractNumber(). 

пример работы пользовательского макроса

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

А на ввод функции вы потратите всего несколько секунд.

Для чего можно использовать?

Вы можете использовать настраиваемую функцию одним из следующих способов:

  • В формуле, где она может брать исходные данные из вашего рабочего листа и возвращать рассчитанное значение или массив значений.
  • Как часть кода макроса VBA или другой пользовательской функции.
  • В формулах условного форматирования.
  • Для хранения констант и списков данных.

Для чего нельзя использовать пользовательские функции:

  • Любого изменения другой ячейки, кроме той, в которую она записана,
  • Изменения имени рабочего листа,
  • Копирования листов рабочей книги,
  • Поиска и замены значений,
  • Изменения форматирования ячейки, шрифта, фона, границ, включения и отключения линий сетки,
  • Вызова и выполнения макроса VBA, если его выполнение нарушит перечисленные выше ограничения. Если вы используете строку кода, который не может быть выполнен, вы можете получить ошибку RUNTIME ERROR либо просто одну из стандартных ошибок (например, #ЗНАЧЕН!).

Как создать пользовательскую функцию в VBA?

 Прежде всего, необходимо открыть редактор Visual Basic (сокращенно — VBE). Обратите внимание, что он открывается в новом окне. Окно Excel при этом не закрывается.

Самый простой способ открыть VBE — использовать комбинацию клавиш. Это быстро и всегда доступно. Нет необходимости настраивать ленту или панель инструментов быстрого доступа. Нажмите Alt + F11 на клавиатуре, чтобы открыть VBE. И снова нажмите Alt + F11, когда редактор открыт, чтобы вернуться назад в окно Excel.

После открытия VBE вам нужно добавить новый модуль. В него вы будете записывать ваш код. Щелкните правой кнопкой мыши на панели проекта VBA слева и выберите «Insert», затем появившемся справа окне — “Module”.

Справа появится пустое окно модуля, в котором вы и будете создавать свою функцию.

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

  • Пользовательская функция всегда начинается с оператора Function и заканчивается инструкцией End Function.
  • После оператора Function указывают имя функции. Это название, которое вы создаете и присваиваете, чтобы вы могли идентифицировать и использовать ее позже. Оно не должно содержать пробелов. Если вы хотите разделять слова, используйте подчеркивания. Например, Count_Words.
  • Кроме того, это имя также не может совпадать с именами стандартных функций Excel. Если вы сделаете это, то всегда будет выполняться стандартная функция.
  • Имя пользовательской функции не может совпадать с адресами ячеек на листе. Например, имя ABC1234 невозможно присвоить.
  • Настоятельно рекомендуется давать описательные имена. Тогда вы можете легко выбрать нужное из длинного списка функций. Например, имя CountWords позволяет легко понять, что она делает, и при необходимости применить ее для подсчета слов.
  • Далее в скобках обычно перечисляют аргументы. Это те данные, с которыми она будет работать. Может быть один или несколько аргументов. Если у вас несколько аргументов, их нужно перечислить через запятую.
  • После этого обычно объявляются переменные, которые использует пользовательская функция. Указывается тип этих переменных – число, дата, текст, массив.
  • Если операторы, которые вы используете внутри вашей функции, не используют никакие аргументы (например, NOW (СЕЙЧАС), TODAY (СЕГОДНЯ) или RAND (СЛЧИС)), то вы можете создать функцию без аргументов. Также аргументы не нужны, если вы используете функцию для хранения констант (например, числа Пи).
  • Затем записывают несколько операторов VBA, которые выполняют вычисления с использованием переданных аргументов.
  • В конце вы должны вставить оператор, который присваивает итоговое значение переменной с тем же именем, что и имя функции. Это значение возвращается в формулу, из которой была вызвана пользовательская функция.
  • Записанный вами код может включать комментарии. Они помогут вам не забыть назначение функции и отдельных ее операторов. Если вы в будущем захотите внести какие-то изменения, комментарии будут вам очень полезны. Комментарий всегда начинается с апострофа (‘). Апостроф указывает Excel игнорировать всё, что записано после него, и до конца строки.

Теперь давайте попробуем создать вашу первую собственную формулу. Для начала мы создаем код, который будет подсчитывать количество слов в диапазоне ячеек.

Для этого в окно модуля вставим этот код:

Function CountWords(NumRange As Range) As Long
Dim rCell As Range, lCount As Long
    For Each rCell In NumRange
        lCount = lCount + _
          Len(WorksheetFunction.Trim(rCell)) - Len(Replace(WorksheetFunction.Trim(rCell), " ", "")) + 1
    Next rCell
CountWords = lCount
End Function

как создать макрос в Эксель

Я думаю, здесь могут потребоваться некоторые пояснения.

Код функции всегда начинается с пользовательской процедуры Function. В процедуре Function мы делаем описание новой функции.

В начале мы должны записать ее имя: CountWords.

Затем в скобках указываем, какие исходные данные она будет использовать. NumRange As Range означает, что аргументом будет диапазон значений. Сюда нужно передать только один аргумент — диапазон ячеек, в котором будет происходить подсчёт.

As Long указывает, что результат выполнения функции CountWords будет целым числом.

Во второй строке кода мы объявляем переменные.

Оператор Dim объявляет переменные:

rCell — переменная диапазона ячеек, в котором мы будем подсчитывать слова.

lCount — переменная целое число, в которой будет записано число слов.

Цикл For Each… Next предназначен для выполнения вычислений по отношению к каждому элементу из группы элементов (нашего диапазона ячеек). Этот оператор цикла применяется, когда неизвестно количество элементов в группе. Начинаем с первого элемента, затем берем следующий и так повторяем до самого последнего значения. Цикл повторяется столько раз, сколько ячеек имеется во входном диапазоне.

Внутри этого цикла с значением каждой ячейки выполняется операция, которая вычисляет количество слов:

Len(WorksheetFunction.Trim(rCell)) — Len(Replace(WorksheetFunction.Trim(rCell), » «, «»)) + 1

Как видите, это обычная формула Excel, которая использует стандартные средства работы с текстом: LEN, TRIM и REPLACE. Это английские названия знакомых нам русскоязычных ДЛСТР, СЖПРОБЕЛЫ и ЗАМЕНИТЬ.  Вместо адреса ячейки рабочего листа используем переменную диапазона rCell. То есть, для каждой ячейки диапазона мы последовательно считаем количество слов в ней.

Подсчитанные числа суммируются и сохраняются в переменной lCount:

lCount = lCount + Len(WorksheetFunction.Trim(rCell)) — Len(Replace(WorksheetFunction.Trim(rCell), » «, «»)) + 1

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

CountWords = lCount

Функция возвращает в ячейку рабочего листа значение этой переменной, то есть общее количество слов.

Именно эта строка кода гарантирует, что функция вернет значение lCount обратно в ячейку, из которой она была вызвана.  

Закрываем наш код с помощью «End Function».

Как видите, не очень сложно.

Сохраните вашу работу. Для этого просто нажмите кнопку “Save” на ленте VB редактора.

После этого вы можете закрыть окно редактора. Для этого можно использовать комбинацию клавиш Alt+Q. Или просто вернитесь на лист Excel, нажав Alt+F11.

Вы можете сравнить работу с пользовательской функцией CountWords и подсчет количества слов в диапазоне при помощи формул. 

Как использовать пользовательскую функцию в формуле?

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

Чтобы использовать ее, у вас есть две возможности.

Первый способ. Нажмите кнопку fx в строке формул. Среди появившихся категорий вы увидите новую группу — Определённые пользователем. И внутри этой категории вы можете увидеть нашу новую пользовательскую функцию CountWords.

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

Второй способ. Вы можете просто записать эту функцию в ячейку так же, как вы это делаете обычно. Когда вы начинаете вводить имя, Excel покажет вам имя пользовательской в списке соответствующих функций. В приведенном ниже примере, когда я ввел = cou , Excel показал мне список подходящих функций, среди которых вы видите и CountWords.

Можно посчитать этой же функцией и количество слов в диапазоне. Запишите в ячейку С3:

=CountWords(A2:A5)

Нажмите Enter.

Мы только что указали функцию и установили диапазон, и вот результат подсчета: 14 слов.

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

Как видите, результаты одинаковы. Только использовать CountWords() гораздо проще и быстрее.

Различные типы пользовательских функций с использованием VBA.

Теперь мы познакомимся с разными типами пользовательских функций в зависимости от используемых ими аргументов и результатов, которые они возвращают.

Без аргументов.

В Excel есть несколько стандартных функций, которые не требуют аргументов (например, СЛЧИС , СЕГОДНЯ , СЕЧАС). Например, СЛЧИС возвращает случайное число от 0 до 1. СЕГОДНЯ вернет текущую дату. Вам не нужно передавать им какие-либо значения.

Вы можете создать такую ​​функцию и в VBA.

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

Function SheetName() as String
    Application.Volatile
    SheetName = Application.Caller.Worksheet.Name
End Function

Или же можно использовать такой код:

SheetName = ActiveSheet.Name

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

Приведенный выше код определяет результат функции как тип данных String (поскольку желаемый результат — это имя файла, которое является текстом). Если вы не укажете тип данных, то Excel будет определять его самостоятельно.

С одним аргументом.

Создадим простую функцию, которая работает с одним аргументом, то есть с одной ячейкой. Наша задача – извлечь из текстовой строки последнее слово.

Function ReturnLastWord(The_Text As String)
Dim stLastWord As String
'Extracts the LAST word from a text string
    stLastWord = StrReverse(The_Text)
    stLastWord = Left(stLastWord, InStr(1, stLastWord, " ", vbTextCompare))
    ReturnLastWord = StrReverse(Trim(stLastWord))
End Function

Аргумент The_Text — это значение выбранной ячейки. Указываем, что это должно быть текстовое значение (As String).

Оператор StrReverse возвращает текст с обратным порядком следования знаков. Далее InStr определяет позицию первого пробела. При помощи Left получаем все знаки заканчивая первым пробелом. Затем удаляем пробелы при помощи Trim. Вновь меняем порядок следования символов при помощи StrReverse. Получаем последнее слово из текста.

Поскольку эта функция принимает значение ячейки, нам не нужно использовать здесь Application.Volatile. Как только аргумент изменится, функция автоматически обновится.

Использование массива в качестве аргумента.

Многие функции Excel используют массивы значений как аргументы. Вспомните функции СУММ, СУММЕСЛИ, СУММПРОИЗВ.

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

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

Function SumEven(NumRange as Range)
 Dim RngCell As Range
 For Each RngCell In NumRange
 If IsNumeric(RngCell.Value) Then
 If RngCell.Value Mod 2 = 0 Then
 Result = Result + RngCell.Value
 End If
 End If
 Next RngCell
 SumEven = Result
 End Function

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

Function SumEven(NumRange as Variant)

Тип Variant обеспечивает «безразмерный» контейнер для хранения данных. Такая переменная может хранить данные любого из допустимых в VBA типов, включая числовые значения, текст, даты и массивы. Более того, одна и та же такая переменная в одной и той же программе в разные моменты может хранить данные различных типов. Excel самостоятельно будет определять, какие данные передаются в функцию.

В коде есть цикл For Each … Next, который берет каждую ячейку и проверяет, есть ли в ней число. Если это не так, то ничего не происходит, и он переходит к следующей ячейке. Если найдено число, он проверяет, четное оно или нет (с помощью функции MOD).

Все чётные числа суммируются в переменной Result.

Когда цикл будет закончен, значение Result присваивается переменной SumEven и передаётся функции.

С несколькими аргументами.

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

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

Она имеет 3 аргумента: диапазон значений, нижняя граница числового интервала, верхняя граница интервала.

Function GetMaxBetween(rngCells As Range, MinNum, MaxNum)
Dim NumRange As Range
Dim vMax
Dim arrNums()
Dim i As Integer
ReDim arrNums(rngCells.Count)
    For Each NumRange In rngCells
     vMax = NumRange
        Select Case vMax
           Case MinNum + 0.01 To MaxNum - 0.01
              arrNums(i) = vMax
              i = i + 1
           Case Else
               GetMaxBetween = 0
           End Select
    Next NumRange
    GetMaxBetween = WorksheetFunction.Max(arrNums)
End Function

Здесь мы используем три аргумента. Первый из них — rngCells As Range. Это диапазон ячеек, в которых нужно искать максимальное значение. Второй и третий аргумент (MinNum, MaxNum) указаны без объявления типа. Это означает, что по умолчанию к ним будет применён тип данных Variant. В VBA используется 6 различных числовых типов данных. Указывать только один из них — это значит ограничить применение функции. Поэтому более целесообразно, если Excel сам определит тип числовых данных.

Цикл For Each … Next последовательно просматривает все значения в выбранном диапазоне. Числа, которые находятся в интервале от максимального до минимального значения, записываются в специальный массив arrNums. При помощи стандартного оператора MAX в этом массиве находим наибольшее число.

С обязательными и необязательными аргументами.

Чтобы понять, что такое необязательный аргумент, вспомните функцию ВПР (VLOOKUP). Её четвертый аргумент [range_lookup] является необязательным. Если вы не укажете один из обязательных аргументов, получите ошибку. Но если вы пропустите необязательный аргумент, всё будет работать.

Но необязательные аргументы не бесполезны. Они позволяют вам выбирать вариант расчётов.

Например, в функции ВПР, если вы не укажете четвертый аргумент, будет выполнен приблизительный поиск. Если вы укажете его как ЛОЖЬ (или 0), то будет найдено точное совпадение.

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

Чтобы сделать аргумент необязательным, вам просто нужно добавить «Optional» перед ним.

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

Function GetText(textCell As Range, Optional CaseText = False) As String
Dim StringLength As Integer
Dim Result As String
StringLength = Len(textCell)
For i = 1 To StringLength
If Not (IsNumeric(Mid(textCell, i, 1))) Then Result = Result & Mid(textCell, i, 1)
Next i
If CaseText = True Then Result = UCase(Result)
GetText = Result
End Function

Этот код извлекает текст из ячейки. Optional CaseText = False означает, что аргумент CaseText необязательный. По умолчанию его значение установлено FALSE.

Если необязательный аргумент CaseText имеет значение TRUE, то возвращается результат в верхнем регистре. Если необязательный аргумент FALSE или опущен, результат остается как есть, без изменения регистра символов.

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

Только с необязательным аргументом.

Насколько мне известно, нет встроенной функции Excel, которая имеет только необязательные аргументы. Здесь я могу ошибаться, но я не могу припомнить ни одной такой.

Но при создании пользовательской такое возможно.

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

Function UserName(Optional Uppercase As Variant)
    If IsMissing(Uppercase) Then Uppercase = False
    UserName = Application.UserName
    If Uppercase Then UserName = UCase(UserName)
End Function

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

Если аргумент равен FALSE или опущен, то имя пользователя возвращается без каких-либо изменений. Если же аргумент TRUE, то имя возвращается в символах верхнего регистра (с помощью VBA-оператора Ucase). Обратите внимание на вторую строку кода. Она содержит VBA-функцию IsMissing, которая определяет наличие аргумента. Если аргумент отсутствует, оператор присваивает переменной Uppercase значение FALSE.

Можно предложить и другой вариант этой функции.

Function UserName(Optional Uppercase As Variant)
    If IsMissing(Uppercase) Then Uppercase = False
    UserName = Application.UserName
    If Uppercase Then UserName = UCase(UserName)
End Function

В этом случае необязательный аргумент имеет значение по умолчанию FALSE. Если функция будет введена без аргументов, то значение FALSE будет использовано по умолчанию и имя пользователя будет получено без изменения регистра символов. Если будет введено любое значение кроме нуля, то все символы будут преобразованы в верхний регистр.

Возвращаемое значение — массив.

В VBA имеется весьма полезная функция — Array. Она возвращает значение с типом данных Variant, которое представляет собой массив (т.е. несколько значений).

Пользовательские функции, которые возвращают массив, весьма полезны при хранении массивов значений. Например, Months() вернёт массив названий месяцев:

Function Months() As Variant
Months = Array("Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", _
"Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь")
End Function

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

В Office365 и выше можно вводить как обычную формулу, в более ранних версиях – как формулу массива.

А если необходим вертикальный массив значений?

Мы уже говорили ранее, что созданные нами функции можно использовать в формулах Excel вместе со стандартными.

Используем Months() как аргумент функции ТРАНСП:

=ТРАНСП(Months())

Как можно использовать пользовательские функции с массивом данных? Можно применять их для ввода данных в таблицу, как показано на рисунке выше. К примеру, в отчёте о продажах не нужно вручную писать названия месяцев.

Можно получить название месяца по его номеру. Например, в ячейке A1 записан номер месяца. Тогда название месяца можно получить при помощи формулы

=ИНДЕКС(Months();1;A1)

Альтернативный вариант этой формулы:

=ИНДЕКС( {«Январь»; «Февраль»; «Март»; «Апрель»; «Май»; «Июнь»; «Июль»; «Август»; «Сентябрь»; «Октябрь»; «Ноябрь»; «Декабрь»};1;A1)

Согласитесь, написанная нами функция делает формулу Excel значительно проще.

Эта статья откроет серию материалов о пользовательских функциях. Если мне удалось убедить вас, что это стоит использовать или вы хотели бы попробовать что-то новое в Excel, следите за обновлениями;)

Сумма по цвету и подсчёт по цвету в Excel В этой статье вы узнаете, как посчитать ячейки по цвету и получить сумму по цвету ячеек в Excel. Эти решения работают как для окрашенных вручную, так и с условным форматированием. Если…
Проверка данных с помощью регулярных выражений В этом руководстве показано, как выполнять проверку данных в Excel с помощью регулярных выражений и пользовательской функции RegexMatch. Когда дело доходит до ограничения пользовательского ввода на листах Excel, проверка данных очень полезна. Хотите…
Поиск и замена в Excel с помощью регулярных выражений В этом руководстве показано, как быстро добавить пользовательскую функцию в свои рабочие книги, чтобы вы могли использовать регулярные выражения для замены текстовых строк в Excel. Когда дело доходит до замены…
Как извлечь строку из текста при помощи регулярных выражений В этом руководстве вы узнаете, как использовать регулярные выражения в Excel для поиска и извлечения части текста, соответствующего заданному шаблону. Microsoft Excel предоставляет ряд функций для извлечения текста из ячеек. Эти функции…
4 способа отладки пользовательской функции Как правильно создавать пользовательские функции и где нужно размещать их код, мы подробно рассмотрели ранее в этой статье.  Чтобы решить проблемы при создании пользовательской функции, вам скорее всего придется выполнить…

Create Custom Functions in Excel

Excel allows you to create custom functions using VBA, called «User Defined Functions» (UDFs) that can be used the same way you would use SUM() or other built-in Excel functions. They can be especially useful for advanced mathematics or special text manipulation or date calculations prior to 1900. Many Excel add-ins provide large collections of specialized functions.

This article will help you get started creating user defined functions with a few useful examples.

This Page (contents):

  • How to Create a Custom User Defined Function
  • Benefits of User Defined Excel Functions
  • Limitations of UDFs
  • User Defined Function Examples

NOTE: The new LAMBDA Function, available within «Production: Current Channel builds of Excel» is going to revolutionize how custom functions can be used in Excel without VBA.

Watch the Video

How to Create a Custom User Defined Function

  1. Open a new Excel workbook.
  2. Get into VBA (Press Alt+F11)
  3. Insert a new module (Insert > Module)
  4. Copy and Paste the Excel user defined function examples
  5. Get out of VBA (Press Alt+Q)
  6. Use the functions — They will appear in the Paste Function dialog box (Shift+F3) under the «User Defined» category

If you want to use a UDF in more than one workbook, you can save your functions to your personal.xlsb workbook or save them in your own custom add-in. To create an add-in, save your excel file that contains your VBA functions as an add-in file (.xla for Excel 2003 or .xlam for Excel 2007+). Then load the add-in (Tools > Add-Ins… for Excel 2003 or Developer > Excel Add-Ins for Excel 2010+).

Warning! Be careful about using custom functions in spreadsheets that you need to share with others. If they don’t have your add-in, the functions will not work when they use the spreadsheet.

Benefits of User Defined Excel Functions

  • Create a complex or custom math function.
  • Simplify formulas that would otherwise be extremely long «mega formulas».
  • Diagnostics such as checking cell formats.
  • Custom text manipulation.
  • Advanced array formulas and matrix functions.
  • Date calculations prior to 1900 using the built-in VBA date functions.

Limitations of UDF’s

  • Cannot «record» an Excel UDF like you can an Excel macro.
  • More limited than regular VBA macros. UDF’s cannot alter the structure or format of a worksheet or cell.
  • If you call another function or macro from a UDF, the other macro is under the same limitations as the UDF.
  • Cannot place a value in a cell other than the cell (or range) containing the formula. In other words, UDF’s are meant to be used as «formulas», not necessarily «macros».
  • Excel user defined functions in VBA are usually much slower than functions compiled in C++ or FORTRAN.
  • Often difficult to track errors.
  • If you create an add-in containing your UDF’s, you may forget that you have used a custom function, making the file less sharable.
  • Adding user defined functions to your workbook will trigger the «macro» flag (a security issue: Tools > Macros > Security…).

User Defined Function Examples

To see the following examples in action, download the file below. This file contains the VBA custom functions, so after opening it you will need to enable macros.

Download the Example File (CustomFunctions.xlsm)

Example #1: Get the Address of a Hyperlink

The following example can be useful when extracting hyperlinks from tables of links that have been copied into Excel, when doing post-processing on Excel web queries, or getting the email address from a list of «mailto:» hyperlinks.

This function is also an example of how to use an optional Excel UDF argument. The syntax for this custom Excel function is:

=LinkAddress(cell,[default_value])

To see an example of how to work with optional arguments, look up the IsMissing command in Excel’s VBA help files (F1).

Function LinkAddress(cell As range, _ 
                     Optional default_value As Variant) 
  'Lists the Hyperlink Address for a Given Cell 
  'If cell does not contain a hyperlink, return default_value 
  If (cell.range("A1").Hyperlinks.Count <> 1) Then 
      LinkAddress = default_value 
  Else 
      LinkAddress = cell.range("A1").Hyperlinks(1).Address 
  End If 
End Function

Example #2: Extract the Nth Element From a String

This example shows how to take advantage of some functions available in VBA to do some slick text manipulation. What if you had a bunch of telephone numbers in the following format: 1-800-999-9999 and you wanted to pull out just the 3-digit prefix?

This UDF takes as arguments the text string, the number of the element you want to grab (n), and the delimiter as a string (eg. «-«). The syntax for this example user defined function in Excel is:

=GetElement(text,n,delimiter)

Example: If B3 contains «1-800-333-4444″, and cell C3 contains the formula, =GetElement(B3,3,»-«), C3 will then equal «333». To turn the «333» into a number, you would use =VALUE(GetElement(B3,3,»-«)).

Function GetElement(text As Variant, n As Integer, _ 
                    delimiter As String) As String 
    GetElement = Split(text, delimiter)(n - 1)
End Function

Example #3: Return the name of a month

The following function is based on the built-in visual basic MonthName() function and returns the full name of the month given the month number. If the second argument is TRUE, it will return the abbreviation.

=VBA_MonthName(month,boolean_abbreviate)

Example: =VBA_MonthName(3) will return «March» and =VBA_MonthName(3,TRUE) will return «Mar.»

Function VBA_MonthName(themonth As Long, _
   		Optional abbreviate As Boolean) As Variant 
    VBA_MonthName = MonthName(themonth, abbreviate)
End Function

Example #4: Calculate Age for Years Prior to 1900

The Excel function DATEDIF(start_date,end_date,»y») is a very simple way to calculate the age of a person if the dates are after 1/1/1900. The VBA date functions like Year(), Month(), Day(), DateSerial(), DateValue() are able to handle all the Gregorian dates, so custom functions based on the VBA functions can allow you to work with dates prior to 1900. The function below is designed to work like DATEDIF(start_date,end_date,»y») as long as end_date >= start_date.

=AgeInYears(start_date,end_date)

Example: =AgeInYears(«10-Oct-1850″,»5-Jan-1910») returns the value 59.

Function AgeInYears(start_date As Variant, end_date As Variant) As Variant 
    AgeInYears = Year(end_date) - Year(start_date) - _
    Abs(DateSerial(Year(end_date), Month(start_date), _
    Day(start_date)) > DateValue(end_date))
End Function

More Custom Excel Function Examples

For an excellent explanation of pretty much everything you need to know to create your own custom Excel function, I would recommend Excel 2016 Formulas. The book provides many good user defined function examples, so if you like to learn by example, it is a great resource.

  • Rounding Significant Figures in Excel :: Shows how to return #NUM and #N/A error values.
  • UDF Examples — www.ozgrid.com — Provides many examples of user defined functions, including random numbers, hyperlinks, count sum, sort by colors, etc.
  • Build an Excel Add-In — http://www.fontstuff.com/vba/vbatut03.htm — An excellent tutorial that takes you through building an add-in for a custom excel function.

Note: I originally published most of this article in 2004, but I’ve updated it significantly and included other examples, as well as the download file.

Probably one of the coolest benefits of learning VBA is the ability to create your own functions.

In Excel, there are more than 450 functions, and some of them are highly useful in your daily work. But Excel gives you the ability to create a custom function using VBA. Yes, you get it right. USER‌ DEFINED Function, in short UDF, or you can also call it a Custom VBA function.

And there’s one thing that I can say with confidence every aspiring VBA user wants to learn to create a User Defined Function. Don’t you? Say “Yes” in the comment section, if you are one of those people who want to create a custom function.

I’m excited to tell you that this is a COMPLETE GUIDE to help you to create your first custom function using VBA and apart from this I have shared some examples of USER-DEFINED Functions to help you to get inspired.

  1. Here I’ll be using the words User Defined Function, custom function, and UDF interchangeably. So stay with me you are going to be a VBA rock star in the next couple of minutes.
  2. To create a code for the VBA custom function you need to write it, you can’t record it using the macro recorder.

Why You Should Create a Custom Excel Function

As I said, there are a lot of in-built functions in Excel which can help you to solve almost all the problems and do all kinds of calculations. But, sometimes, in specific situations, you need to create a UDF.

And, below I have listed some of the reasons or situations in which you need to go with a custom function.

1. When there is no Function for this

This is one of the common reasons for creating a UDF with VBA, because sometimes that you need to calculate something and there is no specific function for this. I can give you an example of counting words from a cell and for this, I found a UDF can be a perfect solution.

count word udf to learn why creating custom function important

2. Replace a Complex Formula

If you work with formulas, I’m sure you know this thing that complex formulas are hard to read and sometimes harder to understand by others. So a custom function can a solution to this problem because once you create a UDF you don’t need to write that complex formula again and again.

a user defined function can help you avoid long calculations

3. When you don’t want to use SUB Routine

While you can use a VBA code to perform a calculation but VBA codes are not dynamic*. You need to run that code again if you want to update your calculation. But if you convert that code into a function then you don’t need to run that code again and again as you can simply insert it as a function.

How to Create Your First User Defined Function in Excel

OK so look. I have split the entire process into three steps:

  1. Declaring your Procedure as a Function
  2. Defining its Arguments and their Data Type
  3. Add code to Calculate the Desired Value

But let me give you can:

You need to create a function that can return the name of the day from a date value. Well, we have a function that returns the day number for the week but not the name. You got it what I’m saying? Yes?

So, let’s follow the below steps to create your first user-defined function:

  1. First of all, open your visual basic editor by using the shortcut key ALT + F11 or go to Developer Tab and simply click on the “Visual Basic” button.
    "open-vb-editor-to-write-code-for-udf
  2. The next thing is to insert a module, so right-click on the VBA project window and then go to insert, and after that click “Module”. (ALERT: You need to enter a USER‌ DEFINED FUNCTION only into standard modules. Sheet and ThisWorkbook modules both are a special type of module and if you enter a UDF in these two modules, Excel does not recognize that you are creating a UDF).
    "add-a-module-in-vba-editor-to-write-a-udf
  3. The third thing is to define a name for the function and here I’m using “myDayName”. So you must write “Function mydayName”. Why Function before the Name? As you are creating a VBA function so the using the word “Function” tells Excel to treat this code as a function (make sure to read the scope of a UDF ahead in the post)."write-a-name-of-the-custom-vba-function
  4. After that, you need to define arguments for your function. So insert starting parentheses and write “InputDate As Date”. Here InputDate is the Argument’s name and date is its data type. It’s always better to define a data type for the argument.
    "the-next-step-to-add-argument-to-the-user-defined-function
  5. Now, close the parentheses and write “As String”. Here you are defining the data type of the result returns by the function and as you want day name which is a text so its data type should be as “String”. If you want to have the result which is other than a string make sure to define its data type according to that. (Function myDayName(InputDate As Date) As String).
    "after-that-define-data-type-for-the-UDF
  6. In the end, hit ENTER. At this point, your function’s name, its argument, argument’s data type, and function’s data type is defined and you have something like below in your module:
    "vba-custom-function-after-defining-name-arguments
  7. Now within the “Function” and “End Function”, you need to define the calculation or you can say working of this UDF. In Excel, there is a worksheet function called “Text” and we are using the same here. And for this, you need to write the below code and with this code, you are defining the value which should be returned by the function. myDayName = WorksheetFunction.Text(InputDate, “dddddd”)
    "after-writing-code-to-use-within-the-vba-custom-function-1
  8. Now, close your VB editor and go back to the worksheet and in the cell B2, enter “=myDayName(A2)” hit enter and you’ll have the day name.
    "insert-your-custom-vba-function-into-worksheet

Congratulations! You have just created your first User Defined Function. This is the moment of real Joy. Isn’t it? Type “Joy” in the comment section.

How this Function Works and Return Value in a Cell

Your first custom function is here, but the thing is, you need to understand how it works. If I say in simple words, it’s a VBA code but you have used it as a function procedure. Let’s divide it into three parts:

  • You enter it in a Cell as Function and Specify the Input Value.
  • Excel runs the code behind the function and uses the value which you have referred to.
  • You got the result in the cell.

But you need to understand how this function works from inside. So I have split the entire process into three different parts where you can see how the code which you have written for the function actually works.

working-user-defined-function

As you have specified “InputDate” as the argument for the function and when you enter the function in the cell and specify a date, VBA takes that date value and supply it to the text function which you have used in the code.

And in the example which I have mentioned above, the date you have in the cell A1 is 01-Jan-2019.

After that, the TEXT function converts that date into a day using the format code “dddddd” which you have already mentioned in the function code. And that day which is returns by the TEXT function is assigned to the “myDayName”.

So if the result of the TEXT function is Tuesday that value will be assigned to the “myDayName”.

And here the working of the function comes to an end. “myDayName” is the name of the function so any value is which is assigned to “myDayName” will be the result value and the function which you have inserted in the worksheet will return it in the cell.

When you write a code for a custom function there one thing you need to take care that the value which that code return must be assigned to the function’s name.

How to Improve a UDF for Good

Well, you know how to create a custom VBA function.

Now…

There’s one thing you need to take care that the code you have used to function should be good enough to handle all the possibilities. If you talk about the function which you just wrote above can return the day name from a date.

But…

What if the value you have specified will not a date? And if the cell you have referred is blank? There can be other possibilities but I’m sure you got my point.

Right? So, let’s try to improve this custom function which could be able to deal with the above problems. Alright. First of all, you need to change the data type of the argument and use:

InputDate As Variant

With this, your custom function can take any kind of data type as input. Next, we need to use VBA IF statement to check InputDate for some conditions. The first condition is if the cell is blank or not. And for this, you need to use below code:

If InputDate = "" Then
myDayName = ""

This will make the function return blank if the cell you have referred is blank.

One problem is solved, let’s get into the next one. Other than a date there are possibilities that you can have a number or a text. So, for this, you also need to create a condition which should check whether the value referred is an actual date or not.

The code would be:

If IsDate(InputDate) = False Then
myDateName = ""

Here I’m using a blank for both of the conditions, so that if you have large data, you could easily filter values where the input value is not valid. So, after adding the above conditions, the code would look like:

Function myDayName(InputDate As Variant) As String
If InputDate = "" Then
myDayName = ""
Else
If IsDate(InputDate) = False Then
myDateName = ""
Else
myDayName = WorksheetFunction.Text(InputDate, "dddddd")
End If
End If
End Function

And here’s how it works now: I’m sure you can still make some changes in this function but I’m sure you got my point clearly.

How to use a Custom VBA Function

At this point, you’re pretty much clear about how you can create a VBA function in Excel. But once you have it, you need to know how you can use it. And in this part of the post, I’m going to share with you how and where you can use it. So, let’s jump into it.

1. Simply within a Worksheet

Why we create a custom function? Simple. To use it in the worksheet. You can simply enter a UDF in a worksheet by using equal sign and type name of the function and then specify it’s arguments.

insert custom function into a worksheet by typing

You can also enter a user defined function from the function library. Go to Formula Tab ➜ Insert Function ➜ User Defined.

insert custom function into a worksheet from formula

From this list, you can choose the UDF you want to insert.

2. Using in other Sub Procedures and Functions

You can also use a function within other functions or in a “Sub” procedure. Below is a VBA code where you have used the function to get day name for the current date.

Sub todayDay()
MsgBox "Today is " & myDayName(Date)
End Sub

Make sure to read “Scope of a UDF” ahead in this post to learn more on using a function in other procedures.

3. Accessing Functions from Other Workbook

If you have a UDF in one workbook and you want to use it in another workbook or in all the workbooks, you do it by making an add-in for it. Follow these simple steps:

  • First of all, to you need to save the file (in which you have the custom function code) as an add-in.
  • For this, go to the File Tab ➜ Save As ➜ “Excel Add-Ins (.xalm).
save file as add in to use all the custom functions in other wworkbooks
  • After that, double-click on the add-in you and install it.
click on add in to add all theuser defined functions into other workbook

That’s it. Now you can use all of your VBA functions in any of the workbook.

Different Ways to Create a Custom VBA Function [Advanced Level]

At this point, you know about to create a custom function in VBA. But the thing is when we use In-Built functions, they come with different type of arguments.

So in this section of this guide, you gonna learn how to create a UDF with the different type of arguments.

  • Without Any Arguments
  • With Just One Argument
  • With Multiple Arguments
  • Using Array as the Argument

…let’s move ahead.

1. Without Any Arguments

Do you remember about functions like NOW and TODAY where you don’t need to enter any argument?

Yes. You can create a User Defined Function where you don’t need to enter an argument. Let’s do it with an example:

Let’s create a custom function which can return the location of the current file. And here’s the code:

Function myPath() As String
Dim myLocation As String
Dim myName As String
myLocation = ActiveWorkbook.FullName
myName = ActiveWorkbook.Name
If myLocation = myName Then
myPath = "File is not saved yet."
Else
myPath = myLocation
End If
End Function

This function returns the path of the location where the current file is stored and if the workbook is not stored anywhere, it will show a message says “File is not saved yet”.

creating  a user defined function without argument

Now, if you pay close attention to the code of this function, you don’t have defined any argument (within the bracket). You have just defined the data type for the function’s result.

The basic rule of creating a function without argument is a code where you don’t need to input anything.

In simple words, the value you want to have in return from the function should be calculated automatically.

And in this function, you have the same thing.

This code ActiveWorkbook.FullName returns the location of the file and this one ActiveWorkbook.Name returns the name. You don’t need to input anything.

2. With Just One Argument

We have already covered this thing while learning how to create a user-defined function. But let’s dig a bit deeper and create a different function. This is the function which I had created a few months back to extract URL from a hyperlink.

Function giveMeURL(rng As Range) As String
On Error Resume Next
giveMeURL = rng.Hyperlinks(1).Address
End Function

Now in this function, you have just one argument.

simple custom function to extract url from a hyperlink

When you enter this in a cell and then specify the cell where you have a hyperlink, and it will return the URL from the hyperlink. Now in this function, the main work is done by:

rng.Hyperlinks(1).Address

But the rng is what you need to specify. Say “Easy” in the comment section if you find creating a UDF easy.

3. With Multiple Arguments

Normally, most of the Excel’s In-Built Functions have multiple arguments. So it’s a must for you to learn how you create a custom function with multiple arguments.

Let’s take an example: You want to remove particular letters from a text string and want to have the rest of the part.

Well, you have functions like RIGHT and LEN which you are going to use in this custom function. But here we don’t need this. All we need is a custom function using VBA.

So, here’s the function:

Function removeFirstC(rng As String, cnt As Long) As String
removeFirstC = Right(rng, Len(rng) - cnt)
End Functio

OK so look:

vba function with multiple arguments

In this function, you two arguments:

  • rng: In this argument, you need to specify the cell from where you want to remove the first character of a text.
  • cnt: And in the argument, you need to specify the count of the characters to remove (If you want to remove more than one character from the text).

When you enter it in a cell it works something like below:

3.1 Creating a User Defined Function with Optional as well as Required Argument

If you think about the function we have just created in the above example where you have two different arguments, well, both of them are required. And, if you miss any of these you’ll get an error like this.

Now if you think logically, the function we have created is to remove the first character. But here you need to specify the count of the characters to remove. So my point is this argument should be optional and must take one as a default value.

What do you think?

Say “Yes” in the comment section if you agree with me on this.

OK so look. To make an argument optional you just need to add “Optional” before it. Just like this:

But the important thing is to make your code to work with or without the value for that argument. So, our new code for the same function would be like this: Now in the code, if you skip specifying the second argument.

4. Using Array as the Argument

There are few In-built functions which can take arguments as an array and you can also make your custom VBA function to do this.

Let’s do with a simple example where you need to create a function where you sum values from a range where you have numbers and text. Here we go.

Function addNumbers(CellRef As Range)
Dim Cell As Range
For Each Cell In CellRef
If IsNumeric(Cell.Value) = True Then
Result = Result + Cell.Value
End If
Next Cell
addNumbers = Result
End Function

In the above code of the function, we have used an entire range A1:A10 instead of a single value or a cell reference.

a custom vba function to sum number froma alist

By using FOR EACH loop, it will check every cell of the range and sum the value if the cell has a number in it.

The scope of a User Defined Function

In simple words, the scope of a function means if it can be called from other procedures or not. A UDF can have two different types of scopes.

1. Public

You can make your custom function public so that you can call it in all the worksheets of the workbook. To make a Function public you just need to use the word “Public”, just like below.

add pubilc before the name of vba custom function

But a function is a public function by default if you don’t make it private. In all examples we have covered, all are public.

2. Private

When you make a function private you can use it in the procedures of the same module.

add private before the name of vba custom function

Let’s say if you have your UDF in “Module1” you can only use it in procedures you have in “Module1”. And it won’t appear in the function list of the worksheet (when you use = sign and try to type the name) but you can still use it by typing its name and specifying arguments.

Limitations of User Defined Function [UDF]

UDFs are super useful. But they are limited in some of the situations. Here are the few things which I want you to note down and remember while creating a custom function in VBA.

  • You can’t change, delete, or format cells and a range by using a custom function.
  • Also, can’t move, rename, delete, or add worksheets to a workbook.
  • Make a change to another cell’s value.
  • It also can’t make changes to any of the environment options,

…click here read more details from Microsoft’s website.

Is there any difference between an In-Built Function and a User Defined Function?

I’m glad you asked. Well, to answer this question I want to share some of the points which I believe are important for you to know.

  1. Slower Than In-Built: If you compare the speed of inbuilt functions and VBA function, you’ll find earlier is fast. The reason behind this is that the in-built functions are written using C++ or FORTRAN.
  2. Hard to Share Files: We often share files over email and cloud so if you are using any of the custom function you require to share that file in “xlam” format so that other person can also use your custom function.

But as I said above in “Why You Should Create a Custom Excel Function” there are some specific situations when you can go for a VBAcustom function.

Conclusion

Creating a User Defined Function is simple. All you need to do it use “Function” before the name to define it as a function, add arguments, define arguments data type and then define the data type for the return value.

a simple illustration to understand how to create a user defined function

In the end, add code to calculate the value which you want to get in return from the function. This guide which I have shared with your today is the simplest one to learn how to create a custom function in VBA and I’m sure you have found it useful.

But now, tell me one thing.

UDFs are useful, what do you think?

Please share your views with me in the comment section. I’d love to hear from you, and please, don’t forget to share this post with your friends, I am sure they will appreciate it.

  • VBA Functions List – Explained with Examples
  • How to Run a Macro in Excel
  • How to use IF Statement in VBA
  • How to Work with Ranges and Cells in VBA
  • VBA Comment
  • Add New Sheet using a VBA Code

VBA is one of the Advanced Excel Skills, and if you are getting started with VBA, make sure to check out there (What is VBA and Useful Macro Examples and VBA Codes).


Download Article


Download Article

Microsoft Excel has many built-in functions, such as SUM, VLOOKUP, and LEFT. As you start using Excel for more complicated tasks, you may find that you need a function that doesn’t exist. That’s where custom functions come in! This wikiHow teaches you how to create your own functions in Microsoft Excel.

  1. Image titled 259250 1

    1

    Open an Excel workbook. Double-click the workbook in which you want to use the custom-defined function to open it in Excel.

  2. Image titled 259250 2

    2

    Press Alt+F11 (Windows) or Fn+ Opt+F11 (Mac). This opens the Visual Basic Editor.

    Advertisement

  3. Image titled 259250 3

    3

    Click the Insert menu and select New Module. This opens a module window in the right panel of the editor.[1]

    • You can create the user defined function in the worksheet itself without adding a new module, but that will make you unable to use the function in other worksheets of the same workbook.
  4. Image titled 259250 4

    4

    Create your function’s header. The first line is where you will name the function and define our range.[2]
    Replace «FunctionName» with the name you want to assign your custom function. The function can have as many parameters as you want, and their types can be any of Excel’s basic data or object types as Range:

    Function FunctionName (param1 As type1, param2 As type2 ) As return Type
    

    • You may think of parameters as the «operands» your function will act upon. For example, when you use SIN(45) to calculate the Sine of 45 degree, 45 will be taken as a parameter. Then the code of your function will use that value to calculate something else and present the result.
  5. Image titled 259250 5

    5

    Add the code of the function. Make sure you use the values provided by the parameters, assign the result to the name of the function, and close the function with «End Function.» Learning to program in VBA or in any other language can take some time and a detailed tutorial. However, functions usually have small code blocks and use very few features of the language. Some useful elements are:

    • The If block, which allows you to execute a part of the code only if a condition is met. Notice the elements in an If code block: IF condition THEN code ELSE code END IF. The Else keyword along with the second part of the code are optional:
      Function Course Result(grade As Integer) As String
        If grade >= 5 Then
          CourseResult = "Approved"
        Else
          CourseResult = "Rejected"
        End If
      End Function
      
    • The Do block, which executes a part of the code While or Until a condition is met. In the example code below, notice the elements DO code LOOP WHILE/UNTIL condition. Also notice the second line in which a variable is declared. You can add variables to your code so you can use them later. Variables act as temporary values inside the code. Finally, notice the declaration of the function as BOOLEAN, which is a datatype that allows only the TRUE and FALSE values. This method of determining if a number is prime is by far not the optimal, but I’ve left it that way to make the code easier to read.
      Function IsPrime(value As Integer) As Boolean
        Dim i As Integer
        i = 2
        IsPrime = True
        Do
          If value / i = Int(value / i) Then
            IsPrime = False
          End If
          i = i + 1
        Loop While i < value And IsPrime = True
      End Function
      
    • The For block executes a part of the code a specified number of times. In this next example, you’ll see the elements FOR variable = lower limit TO upper limit code NEXT. You’ll also see the added ElseIf element in the If statement, which allows you to add more options to the code that is to be executed. Additionally, the declaration of the function and the variable result as Long. The Long datatype allows values much larger than Integer:
      Public Function Factorial(value As Integer) As Long
        Dim result As Long
        Dim i As Integer
        If value = 0 Then
          result = 1
        ElseIf value = 1 Then
          result = 1
        Else
          result = 1
          For i = 1 To value
            result = result * i
          Next
        End If
        Factorial = result
      End Function
      
  6. Image titled 259250 6

    6

    Close the Visual Basic Editor. Once you’ve created your function, close the window to return to your workbook. Now you can start using your user-defined function.

  7. Image titled 259250 7

    7

    Enter your function. First, click the cell in which you want to enter the function. Then, click the function bar at the top of Excel (the one with the fx to its left) and type =FUNCTIONNAME(), replacing FUNCTIONNAME with the name you assigned your custom function.

    • You can also find your user-defined formula in the «User Defined» category in the Insert Formula wizard—just click the fx to pull up the wizard.
  8. Image titled 259250 8

    8

    Enter the parameters into the parentheses. For example, =NumberToLetters(A4). The parameters can be of three types:

    • Constant values typed directly in the cell formula. Strings have to be quoted in this case.
    • Cell references like B6 or range references like A1:C3. The parameter has to be of the Range datatype.
    • Other functions nested inside your function. Your function can also be nested inside other functions. Example: =Factorial(MAX(D6:D8)).
  9. Image titled 259250 9

    9

    Press Enter or Return to run the function. The results will display in the selected cell.

  10. Advertisement

Add New Question

  • Question

    How can I use these functions in all Excel files?

    Igal Livne

    Igal Livne

    Community Answer

    Save the workbook with the custom class as «Excel Add-In (*.xlam»),» by default Excel will take you to «Addins» folder. Go to Excel Options > Add-ins > Manage: «Excel Addins» — press «Go…» button. Browse for your newly create xlam file.

  • Question

    How can I do well in exams?

    Community Answer

    Read the directions several times, leaving time for you to absorb between readings. Also practice writing VBA to do various things.

  • Question

    How do I know what to write as the function code?

    Community Answer

    In order to create functions, you need a skill called «programming». Excel macros are written in a language called «Visual Basic for Applications», which you will need to learn to be able to write macros. It’s quite easy once you’ve got the hang of it though!

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

  • Use a name that’s not already defined as a function name in Excel or you’ll end up being able to use only one of the functions.

  • Whenever you write a block of code inside a control structure like If, For, Do, etc. make sure you indent the block of code using a few blank spaces or the Tab key. That will make your code easier to understand and you’ll find a lot easier to spot errors and make improvements.

Show More Tips

Thanks for submitting a tip for review!

Advertisement

  • The functions used in this article are, by no means, the best way to solve the related problems. They were used here only to explain the usage of the control structures of the language.

  • VBA, as any other language, has several other control structures besides Do, If and For. Those have been explained here only to clarify what kind of things can be done inside the function source code. There are many online tutorials available where you can learn VBA.

  • Due to security measures, some people may disable macros. Make sure you let your colleagues know the book you’re sending them has macros and that they can trust they’re not going to damage their computers.

Advertisement

About This Article

Article SummaryX

1. Open Excel.
2. Press Alt + F11 to open the Visual Basic editor.
3. Create the function’s name and set the parameter types.
4. Use VB code to write your function.
5. Close the editor.
6. Run your function as you would other functions.

Did this summary help you?

Thanks to all authors for creating a page that has been read 640,189 times.

Is this article up to date?

Понравилась статья? Поделить с друзьями:
  • User defined function for excel
  • Useful word phrase for essay
  • Useful word for speaking
  • Useful word for essay writing
  • Useful word and phrases