Excel vba subs and functions of

Содержание

  1. Встроенные функции VBA
  2. Пользовательские процедуры «Function» и «Sub» в VBA
  3. Аргументы
  4. Необязательные аргументы
  5. Передача аргументов по значению и по ссылке
  6. VBA процедура «Function»
  7. Пример VBA процедуры «Function»: Выполняем математическую операцию с 3 числами
  8. Вызов VBA процедуры «Function»
  9. Вызов VBA процедуры «Function» из другой процедуры
  10. Вызов VBA процедуры «Function» из рабочего листа
  11. VBA процедура «Sub»
  12. VBA процедура «Sub»: Пример 1. Выравнивание по центру и изменение размера шрифта в выделенном диапазоне ячеек
  13. VBA процедура «Sub»: Пример 2. Выравнивание по центру и применение полужирного начертания к шрифту в выделенном диапазоне ячеек
  14. Вызов процедуры «Sub» в Excel VBA
  15. Вызов VBA процедуры «Sub» из другой процедуры
  16. Вызов VBA процедуры «Sub» из рабочего листа
  17. Область действия процедуры VBA
  18. Ранний выход из VBA процедур «Function» и «Sub»

Встроенные функции VBA

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

Список этих функций можно посмотреть в редакторе VBA:

  • Откройте рабочую книгу Excel и запустите редактор VBA (нажмите для этого Alt+F11), и затем нажмите F2.
  • В выпадающем списке в верхней левой части экрана выберите библиотеку VBA.
  • Появится список встроенных классов и функций VBA. Кликните мышью по имени функции, чтобы внизу окна отобразилось её краткое описание. Нажатие F1 откроет страницу онлайн-справки по этой функции.

Кроме того, полный список встроенных функций VBA с примерами можно найти на сайте Visual Basic Developer Centre.

Пользовательские процедуры «Function» и «Sub» в VBA

В Excel Visual Basic набор команд, выполняющий определённую задачу, помещается в процедуру Function (Функция) или Sub (Подпрограмма). Главное отличие между процедурами Function и Sub состоит в том, что процедура Function возвращает результат, процедура Sub – нет.

Поэтому, если требуется выполнить действия и получить какой-то результат (например, просуммировать несколько чисел), то обычно используется процедура Function, а для того, чтобы просто выполнить какие-то действия (например, изменить форматирование группы ячеек), нужно выбрать процедуру Sub.

Аргументы

При помощи аргументов процедурам VBA могут быть переданы различные данные. Список аргументов указывается при объявлении процедуры. К примеру, процедура Sub в VBA добавляет заданное целое число (Integer) в каждую ячейку в выделенном диапазоне. Передать процедуре это число можно при помощи аргумента, вот так:

Sub AddToCells(i As Integer)

...

End Sub

Имейте в виду, что наличие аргументов для процедур Function и Sub в VBA не является обязательным. Для некоторых процедур аргументы не нужны.

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

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

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

Sub AddToCells(Optional i As Integer = 0)

В таком случае целочисленный аргумент i по умолчанию будет равен 0.

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

Передача аргументов по значению и по ссылке

Аргументы в VBA могут быть переданы процедуре двумя способами:

  • ByVal – передача аргумента по значению. Это значит, что процедуре передаётся только значение (то есть, копия аргумента), и, следовательно, любые изменения, сделанные с аргументом внутри процедуры, будут потеряны при выходе из неё.
  • ByRef – передача аргумента по ссылке. То есть процедуре передаётся фактический адрес размещения аргумента в памяти. Любые изменения, сделанные с аргументом внутри процедуры, будут сохранены при выходе из процедуры.

При помощи ключевых слов ByVal или ByRef в объявлении процедуры можно задать, каким именно способом аргумент передаётся процедуре. Ниже это показано на примерах:

Sub AddToCells(ByVal i As Integer)

...

End Sub
В этом случае целочисленный аргумент i передан по значению. После выхода из процедуры Sub все сделанные с i изменения будут утрачены.
Sub AddToCells(ByRef i As Integer)

...

End Sub
В этом случае целочисленный аргумент i передан по ссылке. После выхода из процедуры Sub все сделанные с i изменения будут сохранены в переменной, которая была передана процедуре Sub.

Помните, что аргументы в VBA по умолчанию передаются по ссылке. Иначе говоря, если не использованы ключевые слова ByVal или ByRef, то аргумент будет передан по ссылке.

Перед тем как продолжить изучение процедур Function и Sub более подробно, будет полезным ещё раз взглянуть на особенности и отличия этих двух типов процедур. Далее приведены краткие обсуждения процедур VBA Function и Sub и показаны простые примеры.

VBA процедура «Function»

Редактор VBA распознаёт процедуру Function, когда встречает группу команд, заключённую между вот такими открывающим и закрывающим операторами:

Function

...

End Function

Как упоминалось ранее, процедура Function в VBA (в отличие от Sub), возвращает значение. Для возвращаемых значений действуют следующие правила:

  • Тип данных возвращаемого значения должен быть объявлен в заголовке процедуры Function.
  • Переменная, которая содержит возвращаемое значение, должна быть названа так же, как и процедура Function. Эту переменную не нужно объявлять отдельно, так как она всегда существует как неотъемлемая часть процедуры Function.

Это отлично проиллюстрировано в следующем примере.

Пример VBA процедуры «Function»: Выполняем математическую операцию с 3 числами

Ниже приведён пример кода VBA процедуры Function, которая получает три аргумента типа Double (числа с плавающей точкой двойной точности). В результате процедура возвращает ещё одно число типа Double, равное сумме первых двух аргументов минус третий аргумент:

Function SumMinus(dNum1 As Double, dNum2 As Double, dNum3 As Double) As Double

   SumMinus = dNum1 + dNum2 - dNum3

End Function

Эта очень простая VBA процедура Function иллюстрирует, как данные передаются процедуре через аргументы. Можно увидеть, что тип данных, возвращаемых процедурой, определён как Double (об этом говорят слова As Double после списка аргументов). Также данный пример показывает, как результат процедуры Function сохраняется в переменной с именем, совпадающим с именем процедуры.

Вызов VBA процедуры «Function»

Если рассмотренная выше простая процедура Function вставлена в модуль в редакторе Visual Basic, то она может быть вызвана из других процедур VBA или использована на рабочем листе в книге Excel.

Вызов VBA процедуры «Function» из другой процедуры

Процедуру Function можно вызвать из другой VBA процедуры при помощи простого присваивания этой процедуры переменной. В следующем примере показано обращение к процедуре SumMinus, которая была определена выше.

Sub main()

   Dim total as Double
   total = SumMinus(5, 4, 3)

End Sub

Вызов VBA процедуры «Function» из рабочего листа

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

=SumMinus(10, 5, 2)

VBA процедура «Sub»

Редактор VBA понимает, что перед ним процедура Sub, когда встречает группу команд, заключённую между вот такими открывающим и закрывающим операторами:

VBA процедура «Sub»: Пример 1. Выравнивание по центру и изменение размера шрифта в выделенном диапазоне ячеек

Рассмотрим пример простой VBA процедуры Sub, задача которой – изменить форматирование выделенного диапазона ячеек. В ячейках устанавливается выравнивание по центру (и по вертикали, и по горизонтали) и размер шрифта изменяется на заданный пользователем:

Sub Format_Centered_And_Sized(Optional iFontSize As Integer = 10)

   Selection.HorizontalAlignment = xlCenter
   Selection.VerticalAlignment = xlCenter
   Selection.Font.Size = iFontSize

End Sub

Данная процедура Sub выполняет действия, но не возвращает результат.

В этом примере также использован необязательный (Optional) аргумент iFontSize. Если аргумент iFontSize не передан процедуре Sub, то его значение по умолчанию принимается равным 10. Однако же, если аргумент iFontSize передается процедуре Sub, то в выделенном диапазоне ячеек будет установлен размер шрифта, заданный пользователем.

VBA процедура «Sub»: Пример 2. Выравнивание по центру и применение полужирного начертания к шрифту в выделенном диапазоне ячеек

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

Sub Format_Centered_And_Bold()

   Selection.HorizontalAlignment = xlCenter
   Selection.VerticalAlignment = xlCenter
   Selection.Font.Bold = True

End Sub

Вызов процедуры «Sub» в Excel VBA

Вызов VBA процедуры «Sub» из другой процедуры

Чтобы вызвать VBA процедуру Sub из другой VBA процедуры, нужно записать ключевое слово Call, имя процедуры Sub и далее в скобках аргументы процедуры. Это показано в примере ниже:

Sub main()

   Call Format_Centered_And_Sized(20)

End Sub

Если процедура Format_Centered_And_Sized имеет более одного аргумента, то они должны быть разделены запятыми. Вот так:

Sub main()

   Call Format_Centered_And_Sized(arg1, arg2, ...)

End Sub

Вызов VBA процедуры «Sub» из рабочего листа

Процедура Sub не может быть введена непосредственно в ячейку листа Excel, как это может быть сделано с процедурой Function, потому что процедура Sub не возвращает значение. Однако, процедуры Sub, не имеющие аргументов и объявленные как Public (как будет показано далее), будут доступны для пользователей рабочего листа. Таким образом, если рассмотренные выше простые процедуры Sub вставлены в модуль в редакторе Visual Basic, то процедура Format_Centered_And_Bold будет доступна для использования на рабочем листе книги Excel, а процедура Format_Centered_And_Sized – не будет доступна, так как она имеет аргументы.

Вот простой способ запустить (или выполнить) процедуру Sub, доступную из рабочего листа:

  • Нажмите Alt+F8 (нажмите клавишу Alt и, удерживая её нажатой, нажмите клавишу F8).
  • В появившемся списке макросов выберите тот, который хотите запустить.
  • Нажмите Выполнить (Run)

Чтобы выполнять процедуру Sub быстро и легко, можно назначить для неё комбинацию клавиш. Для этого:

  • Нажмите Alt+F8.
  • В появившемся списке макросов выберите тот, которому хотите назначить сочетание клавиш.
  • Нажмите Параметры (Options) и в появившемся диалоговом окне введите сочетание клавиш.
  • Нажмите ОК и закройте диалоговое окно Макрос (Macro).

Внимание: Назначая сочетание клавиш для макроса, убедитесь, что оно не используется, как стандартное в Excel (например, Ctrl+C). Если выбрать уже существующее сочетание клавиш, то оно будет переназначено макросу, и в результате пользователь может запустить выполнение макроса случайно.

Область действия процедуры VBA

В части 2 данного самоучителя обсуждалась тема области действия переменных и констант и роль ключевых слов Public и Private. Эти ключевые слова так же можно использовать применительно к VBA процедурам:

Public Sub AddToCells(i As Integer)

...

End Sub
Если перед объявлением процедуры стоит ключевое слово Public, то данная процедура будет доступна для всех модулей в данном проекте VBA.
Private Sub AddToCells(i As Integer)

...

End Sub
Если перед объявлением процедуры стоит ключевое слово Private, то данная процедура будет доступна только для текущего модуля. Её нельзя будет вызвать, находясь в любом другом модуле или из рабочей книги Excel.

Помните о том, что если перед объявлением VBA процедуры Function или Sub ключевое слово не вставлено, то по умолчанию для процедуры устанавливается свойство Public (то есть она будет доступна везде в данном проекте VBA). В этом состоит отличие от объявления переменных, которые по умолчанию бывают Private.

Ранний выход из VBA процедур «Function» и «Sub»

Если нужно завершить выполнение VBA процедуры Function или Sub, не дожидаясь её естественного финала, то для этого существуют операторы Exit Function и Exit Sub. Применение этих операторов показано ниже на примере простой процедуры Function, в которой ожидается получение положительного аргумента для выполнения дальнейших операций. Если процедуре передано не положительное значение, то дальнейшие операции не могут быть выполнены, поэтому пользователю должно быть показано сообщение об ошибке и процедура должна быть тут же завершена:

Function VAT_Amount(sVAT_Rate As Single) As Single

   VAT_Amount = 0
   If sVAT_Rate <= 0 Then
      MsgBox "Expected a Positive value of sVAT_Rate but Received " & sVAT_Rate
      Exit Function
   End If

...

End Function

Обратите внимание, что перед тем, как завершить выполнение процедуры FunctionVAT_Amount, в код вставлена встроенная VBA функция MsgBox, которая показывает пользователю всплывающее окно с предупреждением.

Оцените качество статьи. Нам важно ваше мнение:

“Computers are useless. They can only give you answers.” – Pablo Picasso.

 
This post provides a complete guide to using the VBA Sub. I also cover VBA functions which are very similar to Subs.

If you want some quick information about creating a VBA Sub, Function, passing parameters, return values etc. then check out the quick guide below.

If you want to understand all about the VBA Sub, you can read through the post from start to finish or you can check out the table of contents below.

Quick Guide to the VBA Sub

Sub Example
Sub

  • Cannot return a value.
Function

  • Can return a value or object.
  • Can run as Worksheet function.
Create a sub Sub CreateReport()

End Sub

Create a function Function GetTotal() As Long

End Function

Create a sub with parameters Sub CreateReport(ByVal Price As Double)

Sub CreateReport(ByVal Name As String)

Create a function with parameters Function GetTotal(Price As Double)

Function GetTotal(Name As String)

Call a sub Call CreateReport
‘ Or
CreateReport
Call a function Call CalcPrice
‘ Or
CalcPrice
Call a sub with parameters Call CreateReport(12.99)

CreateReport 12.99

Call a function with parameters Call CalcPrice(12.99)

CalcPrice 12.99

Call a function and retrieve value
(cannot use Call keyword for this)
Price = CalcPrice
Call a function and retrieve object Set coll = GetCollection
Call a function with params and retrieve value/object Price = CalcPrice(12)
Set coll = GetCollection(«Apples»)
Return a value from Function Function GetTotal() As Long
    GetTotal = 67
End Function
Return an object from a function Function GetCollection() As Collection
    Dim coll As New Collection
    Set GetCollection = coll
End Function
Exit a sub If IsError(Range(«A1»)) Then
     Exit Sub
End If
Exit a function If IsError(Range(«A1»)) Then
     Exit Function
End If
Private Sub/Private Function
(available to current module)
Private Sub CreateReport()
Public Sub/Public Function
(available to entire project)
Public Sub CreateReport()

Introduction

The VBA Sub is an essential component of the VBA language. You can also create functions which are very similar to subs. They are both procedures where you write your code. However, there are differences and these are important to understand. In this post I am going to look at subs and functions in detail and answer the vital questions including:

  • What is the difference between them?
  • When do I use a sub and when do I use a function?
  • How do you run them?
  • Can I return values?
  • How do I pass parameters to them?
  • What are optional parameters?
  • and much more

 
Let’s start by looking at what is the VBA sub?

What is a Sub?

In Excel VBA a sub and a macro are essentially the same thing. This often leads to confusion so it is a good idea to remember it. For the rest of this post I will refer to them as subs.

A sub/macro is where you place your lines of VBA code. When you run a sub, all the lines of code it contains are executed. That means that VBA carries out their instructions.

 
The following is an example of an empty sub

Sub WriteValues()

End Sub

 
You declare the sub by using the Sub keyword and the name you wish to give the sub. When you give it a name keep the following in mind:

  • The name must begin with a letter and cannot contain spaces.
  • The name must be unique in the current workbook.
  • The name cannot be a reserved word in VBA.

 
The end of the Sub is marked by the line End Sub.

 
When you create your Sub you can add some code like the following example shows:

Sub WriteValues()
    Range("A1") = 6
End Sub

What is a Function?

A Function is very similar to a sub. The major difference is that a function can return a value – a sub cannot. There are other differences which we will look at but this is the main one.

You normally create a function when you want to return a value.

 
Creating a function is similar to creating a sub

Function PerformCalc()

End Function

 
It is optional to add a return type to a function. If you don’t add the type then it is a Variant type by default. This means that VBA will decide the type at runtime.

 
The next example shows you how to specify the return type

Function PerformCalc() As Long

End Function

 
You can see it is simple how you declare a variable. You can return any type you can declare as a variable including objects and collections.

A Quick Comparison

Sub:

  1. Cannot return a value.
  2. Can be called from VBAButtonEvent etc.

Function

  1. Can return a value but doesn’t have to.
  2. Can be called it from VBAButtonEvent etc. but it won’t appear in the list of Macros. You must type it in.
  3. If the function is public, will appear in the worksheet function list for the current workbook.

 
Note 1: You can use “Option Private Module” to hide subs in the current module. This means that subs won’t be visible to other projects and applications. They also won’t appear in a list of subs when you bring up the Macro window on the developer tab.

Note 2:We can use the word procedure to refer to a function or sub

Calling a Sub or Function

When people are new to VBA they tend to put all the code in one sub. This is not a good way to write your code.

It is better to break your code into multiple procedures. We can run one procedure from another.

Here is an example:

' https://excelmacromastery.com/
Sub Main()
    
    ' call each sub to perform a task
    CopyData
    
    AddFormulas
    
    FormatData

End Sub

Sub CopyData()
    ' Add code here
End Sub

Sub AddFormulas()
    ' Add code here
End Sub

Sub FormatData()
    ' Add code here
End Sub

 
You can see that in the Main sub, we have added the name of three subs. When VBA reaches a line containing a procedure name, it will run the code in this procedure.

We refer to this as calling a procedure e.g. We are calling the CopyData sub from the Main sub.

There is actually a Call keyword in VBA. We can use it like this:

' https://excelmacromastery.com/
Sub Main()
    
    ' call each sub to perform a task
    Call CopyData
    
    Call AddFormulas
    
    Call FormatData

End Sub

 
Using the Call keyword is optional. There is no real need to use it unless you are new to VBA and you feel it makes your code more readable.

If you are passing arguments using Call then you must use parentheses around them.

For example:

' https://excelmacromastery.com/
Sub Main()
    
    ' If call is not used then no parentheses
    AddValues 2, 4
    
    ' call requires parentheses for arguments
    Call AddValues(2, 4)
End Sub

Sub AddValues(x As Long, y As Long)

End Sub

How to Return Values From a Function

To return a value from a function you assign the value to the name of the Function. The following example demonstrates this:

' https://excelmacromastery.com/
Function GetAmount() As Long
    ' Returns 55
    GetAmount = 55
End Function

Function GetName() As String
    ' Returns John
    GetName = "John"
End Function

 
When you return a value from a function you will obviously need to receive it in the function/sub that called it. You do this by assigning the function call to a variable. The following example shows this:

' https://excelmacromastery.com/
Sub WriteValues()
    Dim Amount As Long
    ' Get value from GetAmount function
    Amount = GetAmount
End Sub

Function GetAmount() As Long
    GetAmount = 55
End Function

 
You can easily test your return value using by using the Debug.Print function. This will write values to the Immediate Window (View->Immediate window from the menu or press Ctrl + G).

' https://excelmacromastery.com/
Sub WriteValues()
    ' Print return value to Immediate Window
    Debug.Print GetAmount
End Sub

Function GetAmount() As Long
    GetAmount = 55
End Function

Using Parameters and Arguments

We use parameters so that we can pass values from one sub/function to another.

The terms parameters and arguments are often confused:

  • A parameter is the variable in the sub/function declaration.
  • An argument is the value that you pass to the parameter.
' https://excelmacromastery.com/
Sub UsingArgs()

    ' The argument is 56
    CalcValue 56
    
    ' The argument is 34
    CalcValue 34

End Sub

' The parameter is amount
Sub CalcValue(ByVal amount As Long)

End Sub

Here are some important points about parameters:

  • We can have multiple parameters.
  • A parameter is passed using either ByRef or ByVal. The default is ByRef.
  • We can make a parameter optional for the user.
  • We cannot use the New keyword in a parameter declaration.
  • If no variable type is used then the parameter will be a variant by default.

The Format of Parameters

Subs and function use parameters in the same way.

The format of the parameter statement is as follows:

' All variables except arrays
[ByRef/ByVal]  As [Variable Type]

' Optional parameter - can only be a basic type
[Optional] [ByRef/ByVal] [Variable name] As <[Variable Type] = 

' Arrays
[ByRef][array name]() As [Variable Type]

Here are some examples of the declaring different types of parameters:

' https://excelmacromastery.com/
' Basic types

Sub UseParams1(count As Long)
End Sub

Sub UseParams2(name As String)
End Sub

Sub UseParams3(amount As Currency)
End Sub

' Collection
Sub UseParamsColl(coll As Collection)
End Sub

' Class module object
Sub UseParamsClass(o As Class1)
End Sub

' Variant
' If no type is give then it is automatically a variant
Sub UseParamsVariant(value)
End Sub

Sub UseParamsVariant2(value As Variant)
End Sub

Sub UseParamsArray(arr() As String)
End Sub

You can see that declaring parameters looks similar to using the Dim statement to declare variables.

Multiple Parameters

We can use multiple parameters in our sub/functions. This can make the line very long

Sub LongLine(ByVal count As Long, Optional amount As Currency = 56.77, Optional name As String = "John")

We can split up a line of code using the underscore (_) character. This makes our code more readable

Sub LongLine(ByVal count As Long _
            , Optional amount As Currency = 56.77 _
            , Optional name As String = "John")

Parameters With a Return Value

This error causes a lot of frustration with new users of VBA.

If you are returning a value from a function then it must have parentheses around the arguments.

The code below will give the “Expected: end of statement” syntax error.

' https://excelmacromastery.com/
Sub UseFunction()
    
    Dim result As Long
    
    result = GetValue 24.99
    
End Sub


Function GetValue(amount As Currency) As Long
    GetValue = amount * 100
End Function
 

 
vba expected end of statement error

 
 
We have to write it like this

result = GetValue (24.99)

ByRef and ByVal

Every parameter is either ByRef or ByVal. If no type is specified then it is ByRef by default

' https://excelmacromastery.com/
' Pass by value
Sub WriteValue1(ByVal x As Long)

End Sub

' Pass by reference
Sub WriteValue2(ByRef x As Long)

End Sub

' No type used so it is ByRef
Sub WriteValue3(x As Long)

End Sub

 
If you don’t specify the type then ByRef is the type as you can see in the third sub of the example.

The different between these types is:

ByVal – Creates a copy of the variable you pass.
This means if you change the value of the parameter it will not be changed when you return to the calling sub/function

ByRef – Creates a reference of the variable you pass.
This means if you change the value of the parameter variable it will be changed when you return to the calling sub/function.

 
The following code example shows this:

' https://excelmacromastery.com/
Sub Test()

    Dim x As Long

    ' Pass by value - x will not change
    x = 1
    Debug.Print "x before ByVal is"; x
    SubByVal x
    Debug.Print "x after ByVal is"; x

    ' Pass by reference - x will change
    x = 1
    Debug.Print "x before ByRef is"; x
    SubByRef x
    Debug.Print "x after ByRef is"; x

End Sub

Sub SubByVal(ByVal x As Long)
    ' x WILL NOT change outside as passed ByVal
    x = 99
End Sub

Sub SubByRef(ByRef x As Long)
    ' x WILL change outside as passed ByRef
    x = 99
End Sub

 
The result of this is:
x before ByVal is 1
x after ByVal is 1
x before ByRef is 1
x after ByRef is 99

 
You should avoid passing basic variable types using ByRef. There are two main reasons for this:

  1. The person passing a value may not expect it to change and this can lead to bugs that are difficult to detect.
  2. Using parentheses when calling prevents ByRef working – see next sub section

A Little-Known Pitfall of ByRef

There is one thing you must be careful of when using ByRef with parameters. If you use parentheses then the sub/function cannot change the variable you pass even if it is passed as ByRef. 

In the following example, we call the sub first without parentheses and then with parentheses. This causes the code to behave differently.

 
For example

' https://excelmacromastery.com/
Sub Test()

    Dim x As Long

    ' Call using without Parentheses - x will change
    x = 1
    Debug.Print "x before (no parentheses): "; x
    SubByRef x
    Debug.Print "x after (no parentheses): "; x

    ' Call using with Parentheses - x will not change
    x = 1
    Debug.Print "x before (with parentheses): "; x
    SubByRef (x)
    Debug.Print "x after (with parentheses): "; x

End Sub

Sub SubByRef(ByRef x As Long)
    x = 99
End Sub

 
If you change the sub in the above example to a function, you will see the same behaviour occurs.

However, if you return a value from the function then ByRef will work as normal as the code below shows:

' https://excelmacromastery.com/
Sub TestFunc()

    Dim x As Long, ret As Long

    ' Call using with Parentheses - x will not change
    x = 1
    Debug.Print "x before (with parentheses): "; x
    FuncByRef (x)
    Debug.Print "x after (with parentheses): "; x
    
    ' Call using with Parentheses and return - x will change
    x = 1
    Debug.Print "x before (with parentheses): "; x
    ret = FuncByRef(x)
    Debug.Print "x after (with parentheses): "; x


End Sub

Function FuncByRef(ByRef x As Long)
    x = 99
End Function

As I said in the last section you should avoid passing a variable using ByRef and instead use ByVal.

This means

  1. The variable you pass will not be accidentally changed.
  2. Using parentheses will not affect the behaviour.

ByRef and ByVal with Objects

When we use ByRef or ByVal with an object, it only affects the variable. It does not affect the actual object.

If we look at the example below:

' https://excelmacromastery.com/
Sub UseObject()
    
    Dim coll As New Collection
    coll.Add "Apple"
    
    ' After this coll with still reference the original
    CollByVal coll
    
    
    ' After this coll with reference the new collection
    CollByRef coll
    
End Sub

Sub CollByVal(ByVal coll As Collection)
    
    ' Original coll will still reference the original
    Set coll = New Collection
    coll.Add "ByVal"

End Sub

Sub CollByRef(ByRef coll As Collection)
    
    ' Original coll will reference the new collection
    Set coll = New Collection
    coll.Add "ByRef"

End Sub

When we pass the coll variable using ByVal, a copy of the variable is created. We can assign anything to this variable and it will not affect the original one.

When we pass the coll variable using ByRef, we are using the original variable. If we assign something else to this variable then the original variable will also be assigned to something else.

You can see find out more about this here.

Optional Parameters

Sometimes we have a parameter that will often be the same value each time the code runs. We can make this parameter Optional which means that we give it a default value.

It is then optional for the caller to provide an argument. If they don’t provide a value then the default value is used.

In the example below, we have the report name as the optional parameter:

Sub CreateReport(Optional reportName As String = "Daily Report")

End Sub

 
If an argument is not provided then name will contain the “Daily Report” text

' https://excelmacromastery.com/
Sub Main()
    
    ' Name will be "Daily Report"
    CreateReport
    
    ' Name will be "Weekly Report"
    CreateReport "Weekly Report"

End Sub

The Optional parameter cannot come before a normal parameter. If you do this you will get an Expected: Optional error.

VBA Expected Optional

 
 
When a sub/function has optional parameters they will be displayed in square parentheses by the Intellisense.

In the screenshot below you can see that the name parameter is in square parentheses.

 

A sub/function can have multiple optional parameters. You may want to provide arguments to only some of the parameters.

There are two ways to do this:
If you don’t want to provide an argument then leave it blank.

A better way is to use the parameter name and the “:=” operator to specify the parameter and its’ value.

The examples below show both methods:

' https://excelmacromastery.com/
Sub Multi(marks As Long _
            , Optional count As Long = 1 _
            , Optional amount As Currency = 99.99 _
            , Optional version As String = "A")
            
    Debug.Print marks, count, amount, version
    
End Sub


Sub UseBlanks()

    ' marks and count
    Multi 6, 5
    
    ' marks and amount
    Multi 6, , 89.99
    
    ' marks and version
    Multi 6, , , "B"
    
    ' marks,count and version
    Multi 6, , , "F"

End Sub

Sub UseName()

    ' marks and count
    Multi 12, count:=5
    
    ' marks and amount
    Multi 12, amount:=89.99
    
    ' marks and version
    Multi 12, version:="B"
    
    ' marks,count and version
    Multi 12, count:=6, version:="F"

End Sub

 
Using the name of the parameter is the best way. It makes the code more readable and it means you won’t have error by mistakenly adding extra commas.

wk.SaveAs "C:Docsdata.xlsx", , , , , , xlShared
    
wk.SaveAs "C:Docsdata.xlsx", AccessMode:=xlShared

IsMissing Function

We can use the IsMissing function to check if an Optional Parameter was supplied.

Normally we check against the default value but in certain cases we may not have a default.

We use IsMissing with Variant parameters because it will not work with basic types like Long and Double.

' https://excelmacromastery.com/
Sub test()
    ' Prints "Parameter not missing"
    CalcValues 6
    
    ' Prints "Parameter missing"   
    CalcValues
    
End Sub

Sub CalcValues(Optional x)

    ' Check for the parameter
    If IsMissing(x) Then
        Debug.Print "Parameter missing"
    Else
        Debug.Print "Parameter Not missing"
    End If

End Sub

Custom Function vs Worksheet Function

When you create a function it appears in the function list for that workbook.

 
Have a look at the function in the next example.

Public Function MyNewFunction()
    MyNewFunction = 99
End Function

 
If you add this to a workbook then the function will appear in the function list. Type “=My” into the function box and the function will appear as shown in the following screenshot.

 
Worksheet Function
If you use this function in a cell you will get the result 99 in the cell as that is what the function returns.

Conclusion

The main points of this post are:

  • Subs and macros are essentially the same thing in VBA.
  • Functions return values but subs do not.
  • Functions appear in the workbook function list for the current workbook.
  • ByRef allows the function or sub to change the original argument.
  • If you call a function sub with parentheses then ByRef will not work.
  • Don’t use parentheses on sub arguments or function arguments when not returning a value.
  • Use parentheses on function arguments when returning a value.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

In Visual Basic, the functions and sub-procedures play similar roles but have different or unique characteristics. However, both perform a programmed task. They utilize a set or group of commands to deliver the required results. The key difference between the sub and the functions is that a sub-procedure generally does not return a result whereas functions tend to return a result. Hence if there is a need for having a value post execution of tasks, then place the VBA code under a function or otherwise place the code under a sub-procedure. In Excel, there is the availability of large numbers of VBA functions that could be utilized in the development of new VBA codes. Such functions are referred to as Built-in functions. With the increase in the size of a VBA program, both Functions and Sub-procedures play a crucial role in the management and performance of VBA code.

Functions in VBA

A function in VBA can be defined as a procedure that executes a piece of code or instructions and post-execution, it returns the value of the tasks performed. A function is hence invoked using a variable. Functions are directly called in the spreadsheets by using excel based formulas. An excel VBA function is not of executable nature. They help in performing a set of repetitive tasks. Following is the syntax for the VBA function: –

Function <Function name>  (Parameters) as variable type

Piece of codes

End function.

Here is a small example of the VBA function: 

Function CalcArea(a As Double, b As Double) As Double

CalcArea = a * b

End Function

In an excel spreadsheet, place the formula in range A1 as shown below:

Calcarea-formula-added

The following would be the output in range A1 of the excel spreadsheet as shown below: 

Output-in-cell-A1-obtained

The above code is a very simple example of how to program or develop custom functions. A VBA programmer can develop as many custom functions’ basis the need of the program. He can insert a new module and start developing a new function just by naming it by a new unique function name.

Sub in VBA

A sub-procedure in VBA can be defined as a procedure that executes a piece of code or instructions, but post-execution does not return the value of the tasks performed. A sub-procedure, therefore, does not require a variable for getting invoked. An excel VBA sub-routine or a sub-procedure is of executable nature and can be assigned as a macro to any excel based object. Like functions, they help in performing a set of repetitive tasks. Following is the syntax for the VBA sub-procedure: 

Sub  <sub name>  (Parameters) 

Piece of codes

End sub

Here is a small example of a VBA sub-routine: 

sub CalcArea() 

Dim a As Double, b As Double

c = a * b

Sheet3.activate

Sheet3.range(“A1”).value=c

End sub

In an excel module, select run sub/user form present under the Run option:

Selecting-sub/user-form

The following would be the output in range A1 of the excel spread sheet as shown below:

Output-in-cell-A1-obtained

The above code is like functions but the only difference is that in this program, the values are hard coded in the sub-procedure itself whereas, in functions, the values are to be passed by the end user. The following things should be followed when creating a sub-routine: 

  • It should not have any spaces.
  • It should not begin with any number or special character. It can however begin with an underscore or a simple letter.
  • The name of the sub-procedure should not be the same as that of the reserved keywords present in the excel VBA.

To Summarize, the following are the differences between a function and a sub in VBA: 

Function In VBA

Sub In VBA

Functions always return a value after it completes their required set of instructions. Sub does not return a value after it completes its required set of instructions.
Functions do not have any alternate nomenclature in VBA In VBA, Subs are referred to as subprocedures as well as subroutines
To Execute Function, it is to be passed on to the excel sheet beginning with equal to sign. In Short, they are invoked as excel based formulas. To execute a sub in VBA, it can be run or could be executed through Project explorer or by assigning it as a macro on excel objects.

VBA has two types of procedures for creating and executing codes: Subroutine (or simply Sub) and Function.

So far, the examples in this tutorial have always been tied to a Sub. From here on, we will continue to assume that it is a Sub unless it is explicit that it is a Function.


Subroutine

A Sub can be used to execute another Sub:

    Sub sub_main()
        sub_auxiliary1
        sub_auxiliary2
    End Sub
    Sub sub_auxiliary1()
        MsgBox "One Sub executing another Sub"
    End Sub
    Sub sub_auxiliary2()
        MsgBox "One Sub executing a second Sub"
    End Sub

For this and further examples, just run the sub_main. By clicking anywhere between the line Sub sub_main() and the first End Sub.

A Sub can also accept an argument:

    Sub sub_main()
        sub_argument(10) '10 is an argument
    End Sub
    Sub sub_argument(x as Integer)
        MsgBox x
    End Sub

You can assign an argument to the Sub using a single space:

    sub_argument 10 '10 is an argument

Or multiple arguments:

    Sub sub_main()
        Dim score As Single
        Dim student As String

        score=10
        student="Paulo"
        Call sub_argument (score, student) 'score is an argument, student is another argument
    End Sub
    Sub sub_argument(s_exam as Single, name as String)
        MsgBox name & "'s score was " & s_exam
    End Sub

To have more than one argument into a Sub, you can use the Call instruction before the name of the Sub you want to call.

You can also execute a Sub with multiple arguments omitting the Call instruction and the parentheses:

sub_argument score, student

Have the practice of declaring the variables in the same data types that the Sub requires as arguments.

E.g.score and s_exam.

Subs can also be accessed from different modules:


Types of Sub

The types of Sub available are Private and Public:

Private Sub

An undefined Sub is considered Public by VBA.


Functions

Functions work similarly to Subroutines with arguments. The main difference is that the Function will necessarily return a value and should be called by some other procedure.

    Sub sub_main()
        result = multiply_2(10)
        Msgbox result
    End Sub
    Function multiply_2(x As Single)
        multiply_2 = x*2
    End Function

It is not possible to pass arguments to a function through the single space if it is being associated with a variable.

    result = multiply_2 10 'Will result in error!

Note that:

MsgBox resultado 'It will not result in an error because there is no association.

You can not run a Function by itself. It is necessary to be called by another procedure.

E.g. Sub sub_main().

Once defined, functions can be used normally by the user in the Excel spreadsheet environment. Just call by the name of the function, as with any other predefined function (SUM, AVERAGE, etc.).

User Defined Function

We can also define in the declaration the type of result that the Function will return:

  Function multiply_2(x As Single) As Integer
      multiply_2 = x*2
  End Function

Note that now the function will only return rounded results, given the return specification As Integer.

There are many predefined functions in VBA. MsgBox is one of them.

        Msgbox "This should be shown" 'MsgBox works without the parentheses
        Msgbox ("This should be shown") 'and works with the parentheses

Naming a Function

When you create a function it needs to be followed by a name that must comply with the following rules:

  • It must initiate with an alphabetical character
  • It must not contain especial characters, such as: #, $, %, &, !
  • It must not contain whitespace characters, dots or commas
  • It must not be a VBA reserved word like: And, Or, Sub

Function Errors

Question: What if the user inserts unexpected values into my function?

Answer: Create an error to warn him.

This procedure can be done through the predefined CVErr function, which uses an integer value to specify an error.

The possible value it accepts are:

  • 2000 (ou xlErrNull) which returns a #NULL! error
  • 2007 (ou xlErrDiv0) which returns a #DIV/0 error
  • 2015 (ou xlErrValue) which returns a #VALUE! error
  • 2023 (ou xlErrRef) which returns a #REF! error
  • 2029 (ou xlErrName) which returns a #NAME? error
  • 2036 (ou xlErrNum) which returns a #NUM! error
  • 2042 (ou xlErrNA) which returns a #N/A error

Compare how an User Defined Function (UDF) to calculate the area of a triangle should be changed to apply the CVErr

Function AreaTriangle(Base As Single, Height As Single) As Double
    'As Double above specifies the return type of AreaTriangle
    AreaTriangle = (Base * Height) / 2

End Function

Negative values are not expected for the area calculation, so let’s create an error if the user enters them:

Function AreaTriangle(Base As Single, Height As Single) As Variant 
'As Variant is defining the data type of AreaTriangle

    If Base < 0 Or Height < 0 Then
        AreaTriangle = CVErr(2036)
    Else
        AreaTriangle = (Base * Height) / 2
    End If

End Function

In this way, if the user inserts negative values, the following error will appear in the cell of the function: NÚM!

The data type of CVErr(2036) is Error. This data type besides not being common is also incompatible with numeric data (that will be necessary for the calculation of the area). Therefore we assign to AreaTriangle the data type Variant. In this way, AreaTriangle will accept both the Error data type, if it occurs, and the Double data type, which will be returned if the calculation proceeded properly.


Sub VS Function

  • Subroutines do not return values if called. Functions return values
  • Subroutines can be assigned to buttons and shapes in Excel, Functions can’t
  • Functions created in VBA can be used in your Excel worksheet

By default the predefined Excel functions are named in all capital letters.

Mixing uppercase and lowercase letters is a good way to differentiate from Excel and make explicit the functions that were created by the user.



Consolidating Your Learning

Suggested Exercises



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

A VBA Function can accept parameters and return results. Functions, however, can’t be executed directly. On the other hand a VBA Sub procedure can be executed directly and can also accept parameters. Procedures, however, do not return values.

We often use Subs and Functions often not thinking about their true potential and how much we can squeeze out of a regular VBA Function. Let’s start with a reminder how both differ from each other and then dive into the details.

Below structure resembles a VBA Sub and VBA Function:

'This is a Sub (procedure). Subs can only take arguments, they don't return results
Sub SomeSub(...)
  ...
End Sub

'This is a simple Function
Function SomeFunc(...) as ... 'Functions can take arguments and can return results
 ...
End Function 

Below are simple examples of Subs and Functions:

'Example Sub
Sub SayHello(name as String)
  Debug.Print "Hello " & name
End Sub

'Example Function
Function Add2Numbers(num1 as Long, num2 as Long) as Long 
  Add2Numbers = num1 + num2
End Function 

'Below Sub tests the Function Add2Numbers
Sub TestAdd2Numbers()
  Debug.Print Add2Numbers(1,2)
End Sub
'Result: 3

VBA Sub procedure syntax

The code block of a VBA Sub procedure is marked by the Sub and End Sub statements.
VBA Sub procedure

VBA Function procedure syntax

The code block of a VBA Function is marked by the Function and End Function statements.
VBA Function

VBA Function vs VBA Sub

We often tend to mix up procedures, Subs and Functions in VBA. So let’s get it right this time. There are 2 main differences between VBA Procedures (Subs) and VBA Functions:

  • VBA Functions return values, VBA Subs don’t
  • You can execute a VBA Sub, you can’t execute VBA Functions – they can only be executed by VBA Subs

Executing Functions and Subs

Although I provided examples above there are multiple ways to execute a VBA Function and a VBA Sub:

'An example VBA Procedure
Sub TestSub(arg as Long)
..
End Sub

'An example VBA Function
Function TestFunction(arg as Long) as String
...
End Function 


'HOW TO RUN FUNCTIONS AND PROCEDURES
Sub Test()
  Dim result

  '---RUN A FUNCTION---
  
 'Example 1: Run a Sub with brackets with the Call operator
  Call TestSub (10) 

  'Example 2: Run a Sub without brackets and without the Call operator
  TestSub 10

  '---RUN A FUNCTION---
  'Example: Functions are meant to return values so then need to be used with brackets
  result = TestFunction(1)
End Sub

Passing arguments ByVal and ByRef

The common knowledge is that only VBA Functions can return values. That indeed is mostly true. However, instead of a value (the result of the Function), we can assign values to variables that can be passed to the procedure by reference. What does that mean?

Variables can either by passed to a procedure (Function, Sub etc.) by their value or their reference.
Passing by value translates to making a copy of the variable. Thus any changes to the copy will not be reflected in the original variable.
Passing by reference is passing the address of the variable to the procedure. This means that any changes to a argument will be reflected in the original variable.
ByVal vs ByRef

By default all arguments are passed to procedures ByVal, so that no changes can be made to the original variables

ByVal and ByRef examples

Let’s look at some examples now:

Sub SetValueByVal(ByVal someLong As Long)
    someLong = 10
End Sub
Sub SetValueByRef(ByRef someLong As Long)
    someLong = 10
End Sub

Sub Test()
    Dim someLong As Long
    someLong = 1
    
    SetValueByVal someLong
    Debug.Print someLong 'Result: 1 (no change)
    
    SetValueByRef someLong
    Debug.Print someLong 'Result: 10
End Sub

When passing by value the variable someLong is not modified. However, when we pass it by reference its value is changed within the Sub procedure.

Objects and arrays are always passed by reference, because objects are in fact references (e.g. a Collection). Beware in such cases not to modify referenced objects by mistake!

Passing arrays to Subs and Functions

You can also easily pass arrays to Subs or Functions, even redefining their length. See example below:

Sub ChangeLength(arr() As Long)
    ReDim arr(5) As Long
End Sub

Sub Test()
    Dim arr() As Long
    ReDim arr(2) As Long
    Debug.Print UBound(arr) 'Result: 2
    ChangeLength arr
    Debug.Print UBound(arr) 'Result: 5
End Sub

Optional parameters

VBA Functions and Subs permit optional parameters, ones that need not be provided when executing the Function or Sub. It is a good practice to specify the default value for such parameters. See example below:

Sub SayHi(name As String, Optional surname As String = vbNullString)
    Debug.Print "Hi there, " & name & IIf(surname = vbNullString, "", " " & surname)
End Sub

Sub Test()
    Call SayHi("John") 'Result: "Hi there, John"
    
    Call SayHi("John", "Smith") 'Result: "Hi there, John Smith"
End Sub

You can verify if a parameter has not been passed to an Sub or Function by using the IsMissing function. The IsMissing function works however only for Variant type parameters. See the same SayHi procedure as above, this time with the IsMissing function.

Sub SayHi(name As String, Optional surname As Variant)
    Debug.Print "Hi there, " & name & IIf(IsMissing(surname), "", " " & CStr(surname))
End Sub

Sub Test()
    Call SayHi("John") 'Result: "Hi there, John"
    
    Call SayHi("John", "Smith") 'Result: "Hi there, John Smith"
End Sub

Dynamic parameter list

Say you want to create a VBA function like the Excel SUM or AVERAGE formulas – that can be provided with a dynamic list of parameters. VBA extends a neat solution for such a scenario called the ParamArray.

Public Function MySUM(ParamArray args())
    For Each arg In args
        MySUM = MySUM + arg
    Next arg
End Function

Sub Test()
    Debug.Print MySUM(1, 2, 3, 4) 'Result: 10
End Sub

The ParamArray transforms a list of Variant variables passed as parameters into a neat Variant array.

Read more on the ParamArray in this post.

Понравилась статья? Поделить с друзьями:
  • Excel vba sub или function
  • Excel vba sub аргументы
  • Excel vba sub workbooks
  • Excel vba sub return
  • Excel vba sub range