Vba excel private sub что это

When writing VBA macros, the concept of Private or Public is important. It defines how VBA code within one module can interact with VBA code in another module. This concept applies to both Private Subs and Private Functions.

As a simple analogy – on social media, you can set parts of your profile so that everybody can see it (Public), or only those you allow, such as friends or followers, to see it (Private). The Private vs. Public concept in VBA is similar, but since we’re talking about VBA here, it’s not quite as straightforward.

Before we launch into the difference between Public and Private, we first need to understand what Modules are and how they work.

Modules

Modules are the place where VBA code is written and stored. There are many different module types in Excel, and we use each module for a different purpose.

Worksheet Modules

Worksheet Modules are generally used to trigger code related to that specific worksheet. Each worksheet contains its own module, so if there are 6 worksheets, then we have 6 Worksheet Modules.

Worksheet Module - Private Sub

In the screenshot above, the VBA code is contained within the Worksheet Module of Sheet1. As we have used the Worksheet_Activate event, the code is triggered only when Sheet1 is activated. Any event-based code (such as worksheet activation) in a Worksheet Module only applies to the worksheet in which the code is stored.

Workbook Module

The Workbook Module is generally used to trigger code related to workbook-level events.

Workbook Module - Public Sub

In the screenshot above, we have used the Workbook_Open event. Therefore, the VBA code will run when a workbook is opened. Every workbook has its own module.

UserForm Module

UserForm Modules generally contain code that relates to UserForm events. Each UserForm has its own module.

UserForm Private Sub

In the screenshot above, the VBA code will run when the user clicks on CommandButton1 in the UserForm.

Standard Modules

Standard Modules are not related to any specific objects and do not have any events related to them. Therefore, standard Modules are not triggered by user interaction. If we are relying on triggered events, we need the Workbook, Worksheet, or UserForm Modules to track the event. However, that event may then call a macro within a Standard Module.

TIP: Find out how to run a macro from another macro here: Run a macro from a macro (from another workbook)

Standard Module

The screenshot above shows a code that password protects the ActiveSheet, no matter which workbook or worksheet.

Other Module Types

The final type of VBA module available is a Class Module. These are for creating custom objects and operate very differently from the other module types. Class Modules are outside the scope of this post.

The terms Public and Private are used in relation to Modules. The basic concept is that Public variables, Subs, or Functions can be seen and used by all modules in the workbook, while Private variables, Subs, and Functions can only be used by code within the same module.

Declaring a Private Sub or Function

To treat a Sub or Function as Private, we use the Private keyword at the start of the name.

Private Sub nameOfSub()
Private Function nameOfFunction()

Declaring a Public Sub or Function

To treat a Sub or Function as Public, we can use the Public keyword. However, if the word Public or Private is excluded, VBA treats the sub/function as if it were public. As a result, the following are all Public, even though they do not all include the keyword.

Public Sub nameOfSub()
Sub nameOfSub()
Public Function nameOfFunction()
Function nameOfFunction()

Let’s look at Subs and Functions in a bit more detail

Sub procedures (Subs)

When thinking about the difference between a Public Sub and a Private Sub, the two primary considerations are:

  • Do we want the macro to appear in the list of available macros within Excel’s Macro window?
  • Do we want the macro to be run from another Macro?

Does it appear in the Macro window?

One of the most important features of Private subs is that they do not appear in Excel’s Macro window.

Let’s assume Module1 contains the following two macros:

Private Sub NotVisible()

MsgBox "This is a Private Sub"

End Sub
Public Sub IAmVisible()

MsgBox "This is a Public Sub"

End Sub

The Macro dialog box only displays the Public sub.

Macro Windows excludes Private Subs

I don’t want you to jump to the conclusion that all Public Subs will appear in the Macro window, as that is not true. Any Public sub which requires arguments, also does not appear in this window, but it can still be executed if we know how to reference it.

Can the code be run from another macro?

When we think about Private Subs, it is best to view them as VBA code that can only be called by other code within the same module. So, for example, if Module1 contains a Private Sub, it cannot be called by any code in another module.

Using a simple example, here is a Private Sub in Module1:

Private Sub ShowMessage()

MsgBox "This is a Private Sub"

End Sub

Now let’s try to call the ShowMessage macro from Module2.

Sub CallAPrivateMacro()

Call ShowMessage

End Sub

Running CallAPrivateMacro generates an error, as the two macros are in different modules.

Private Sub Error Message

If the ShowMessage macro in Module1 were a Public Sub, it would execute correctly.

There are many ways to run a macro from another macro. One such method allows us to run a Private Sub from another Module. If we use the Application.Run command, it will happily run a Private sub. Let’s change the code in Module2 to include the Application.Run command:

Sub CallAPrivateMacro()

Application.Run "ShowMessage"

End Sub

Instead of an error, the code above will execute the ShowMessage macro.

Code executes correctly

Working with object-based module events

Excel creates the Worksheet, Workbook, and UserForm Module events as Private by default, but they don’t need to be. If they are changed to Public, they can be called from other modules. Let’s look at an example.

Enter the following code into the Workbook Module (notice that I have changed it to a Public sub).

Public Sub Workbook_Open()

MsgBox "Workbook Opened"

End Sub

We can call this from another macro by using the object’s name followed by the name of the Public sub.

Sub RunWorkbook_Open()

Call ThisWorkbook.Workbook_Open

End Sub

This means that we can run the Workbook_Open event whenever we need to. If the sub in the Workbook Module is Private, we can still use the Application.Run method noted above.

Functions

VBA functions are used to return calculated values. They have two primary uses:

  • To calculate a value within a cell on a worksheet (known as User Defined Functions)
  • To calculate a value within the VBA code

Like Subs, Functions created without the Private or Public declaration are treated as Public.

Calculating values within the worksheet (User Defined Functions)

User Defined Functions are worksheet formulas that operate similarly to other Excel functions, such as SUMIFS or XLOOKUP.

The following code snippets are included within Module1:

Public Function IAmVisible(myText As String)

IAmVisible = myText

End Function
Private Function NotVisible(myText As String)

NotVisible = myText

End Function

If we look at the Insert Function dialog box, the IAmVisible function is available as a worksheet function.

UDF Visible

Functions must be declared in a Standard Module to be used as User Defined Functions in an Excel worksheet.

Function within the VBA Code

Functions used within VBA code operate in the same way as subs; Private functions should only be visible from within the same module. Once again, we can revert to the Application.Run command to use a Private function from another module.

Let’s assume the following code were entered into Module2:

Sub CallAPrivateFunction()

MsgBox Application.Run("NotVisible", "This is a Private Function")

End Sub

The code above will happily call the NotVisible private function from Module1.

Variables

Variables hold values or references to objects that change while the macro runs. Variables come in 3 varieties, Public, Private and Dim.

Public Variables

Public variables must be declared at the top of the code module, directly after the Option Explicit statement (if you have one), and before any Subs or Functions. 

The following is incorrect and will create an error if we try to use the Public Variable.

Option Explicit

Sub SomethingElseAtTheTop()
MsgBox "Public Variable is not first"
End Sub

Public myPublicMessage As String

The correct approach would be: (The Public variable is declared before any subs or functions):

Option Explicit

Public myPublicMessage As String

Sub SomethingAfterPrivateVariables()
MsgBox "Public Variable is first"
End Sub

As it is a Public variable, we can use and change the variable from any module (of any type) in the workbook. Look at this example code below, which could run from Module2:

Sub UsePublicVariable()

myPublicMessage = "This is Public"
MsgBox myPublicMessage

End Sub

Private Variables

Private Variables can only be accessed and changed by subs and functions within the same Module. They too, must also be declared at the top of the VBA code.

The following demonstrates an acceptable usage of a Private variable.

Module1:

Option Explicit

Private myPrivateMessage As String


Sub UsePrivateVariable()

myPrivateMessage = "This is Private"
MsgBox myPrivateMessage

End Sub

Dim Variables

Most of us learn to create variables by using the word Dim. However, Dim variables behave differently depending on how they are declared.

Dim variables declared within a Sub or Function can only be used within that Sub or Function. In the example below, the Dim has been declared inside a Sub called CreateDim, but used within a sub called UseDim. If we run the UseDim code, it cannot find the Dim variable and will error.

Sub CreateDim()

Dim myDimMessage

End Sub
Sub UseDim()

myDimMessage = "Dim inside Sub"

MsgBox myDimMessage

End Sub

If a Dim variable is created at the top of the module, before all the Subs or Functions, it operates like a Private variable. The following code will run correctly.

Option Explicit

Dim myDimMessage


Sub UseDim()

myDimMessage = "Dim inside Sub"

MsgBox myDimMessage

End Sub

Does this really matter?

You might think it sounds easier to create everything as Public; then it can be used anywhere. A logical, but dangerous conclusion. It is much better to control all sections of the code. Ask yourself, if somebody were to use your macro from Excel’s Macro window, should it work? Or if somebody ran your function as a User Defined Function, should it work? Answers to these questions are a good guiding principle to help decide between Public and Private.

It is always much better to limit the scope of your Subs, Functions, and variables initially, then expand them when required in specific circumstances.


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

In this Article

  • Public vs. Private Sub Procedures
    • Excel Macro Window
  • Procedures with Arguments
  • Using Procedures between Modules in your VBA Project
    • Private Modules
    • Accessing a Private Procedure from a Different Module

This tutorial will explain the difference between public and private declarations in VBA and how to specify modules as private.

Public vs. Private Sub Procedures

Procedures (Sub and Functions) can be declared either Private or Public in VBA. If they are Public, it means that you would be able to see them from within the Excel Macro Window and they can be called from anywhere within your VBA Project.  If they are Private, they cannot be seen in the Excel Macro Window and are only available to be used within the Module in which they are declared (using normal methods, see the bottom of this article for ways to access private procedures from other modules).

Public functions can be called like built-in Excel functions in the Excel worksheet.

Note: Variables and Constants can also be Public or Private.

Excel Macro Window

By default, Excel Macros (most VBA Procedures) are visible to workbook users in the Macro Window:

vba publicvsprivate macro window

These are considered Public procedures. You can explicitly define procedures as public by adding “Public” before the Sub statement:

Public Sub HelloWorld()
   MsgBox "Hello World"
End Sub

If you don’t define the procedure as Public, it will be assumed Public.

To declare a procedure as Private, simply add “Private” before the procedure sub statement:

Private Sub HelloEveryone()
MsgBox "Hello Everyone"
End Sub

The second procedure would not be visible in the Macro window to Excel users, but can still by used in your VBA code.

vba publicvsprivate 2

Procedures with Arguments

Sub procedures can have arguments. Arguments are inputs to the sub procedure:

Sub Hello(strName as string)
   MsgBox "Hello " & strName
End Sub

If a sub procedure has arguments, it will never appear in the Macro Window regardless of if its declared Public because there is no way to declare the arguments.

Functions also will never appear in the Macro Window, regardless of if they are declared Public.

vba publicvsprivate macro window 2

Public functions in Excel are able to be used directly in a worksheet as a ‘User Defined Function’ (UDF). This is basically a custom formula that can be called directly in a worksheet. They can be found in the ‘User Defined’ category in the ‘Insert Function window or can be typed directly into a cell.

vba publicvsprivate excel function

Using Procedures between Modules in your VBA Project

Public procedures can be called from any module or form within your VBA Project.

vba publicvsprivate call sub

Attempting to call a private procedure from a different module will result in an error (Note: see bottom of this article for a work around).

vba publicvsprivate call private sub

Note: Public procedures and variables in class modules behave slightly differently and are outside the scope of this article.

Different modules, can store procedures with the same name, provided they are both private.

If two or more procedures have the same name and are declared public you will get an ‘Ambiguous Name detected’ compile error when running code.

vba publicvsprivate ambigious

Private Modules

By default, modules are public.

To make a module private, you put the following keyword at the top of the module.

Option Private Module

If you declare a module as private, then any procedures in the module will not be visible to Excel users. Function procedures will not appear in the Insert Function window but can still be used in the Excel sheet as long as the user knows the name of the function!

vba publicvsprivate private function excel

Sub procedures will not appear in the Macro Window but will still be available to be used within the VBA project.

Accessing a Private Procedure from a Different Module

As mentioned above, Private Procedures are inaccessible in other code modules by “normal” methods. However, you can access private procedures by using the Application.Run command available in VBA.

Consider the following 3 modules.

vba publicvsprivate multi modules

Module 2 is a Private Module with a Public Sub Procedure, whereas Module3 is Public module with a Private Sub Procedure.

In Module1, we can call Hello World  – the Option Private Module at the top does not prevent us from calling the Sub Procedure – all it serves to do is hide the Sub Procedure in the Macro Window.

We also do not need the Call statement – it is there to make the code easier to read.

The code could also look like this below:

Sub CallHelloFromPrivate()
'call a sub from a Private Module
   HelloWorld
End Sub

We can also run the HelloWorld Sub Procedure by using the VBA Application.Run command.

In Module3 however, the GoodMorningWorld procedure has been declared Private.   You cannot call it from another module using ‘normal’ means ie the Call statement.

You have to use Application.RunCommand to run a Private Sub from another module.

Sub CallGoodMorning()
'run a private sub from a public module
   Application.Run ("GoodMorningWorld")
End Sub

Notice the when you use the Application.RunCommand command, you have to put the Sub Procedure name within inverted commas.

If we do try to use the Call statement to run the GoodMorningWorld Sub Procedure, an error would occur.  

vba publicvsprivate multi modules error

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

“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.)

275

18 февраля 2012 года

pashulka

985 / / 19.09.2004

Инструкция Sub

Описывает имя, аргументы и текст программы, составляющий тело процедуры Sub.

Синтаксис

[Private | Public] [Static] Sub имя [(списокАргументов)]
[инструкции]
[Exit Sub]
[инструкции]
End Sub

Синтаксис инструкции Sub содержит следующие элементы:

ЭлементОписание

Public — Необязательный. Указывает, что процедура Sub доступна для всех других процедур во всех модулях. При использовании в личном модуле (модуле, который содержит инструкцию Option Private) такая процедура является недоступной вне проекта.

Private — Необязательный. Указывает, что процедура Sub доступна для других процедур только того модуля, в котором она описана.

Static — Необязательный. Указывает, что локальные переменные процедуры Sub сохраняются в промежутках времени между вызовами этой процедуры. Атрибут Static не действует на переменные, описанные вне процедуры Sub, даже если они используются в процедуре.

имя — Обязательный. Имя процедуры Sub, удовлетворяющее стандартным правилам именования переменных.

списокАргументов — Необязательный. Список переменных, представляющий аргументы, которые передаются в процедуру Sub при ее вызове. Имена переменных разделяются запятой.

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

Аргумент списокАргументов имеет следующий синтаксис и элементы:

[Optional] [ByVal | ByRef] [ParamArray] имяПеременной[( )] [As тип] [= поУмолчанию]

ЭлементОписание

Optional — Необязательный. Ключевое слово, указывающее, что аргумент не является обязательным. При использовании этого элемента все последующие аргументы, которые содержит списокАргументов, также должны быть необязательными и быть описаны с помощью ключевого слова Optional. Все аргументы, описанные как Optional, должны иметь тип Variant. Не допускается использование ключевого слова Optional для любого из аргументов, если используется ключевое слово ParamArray.

ByVal — Необязательный. Указывает, что этот аргумент передается по значению.

ByRef — Необязательный. Указывает, что этот аргумент передается по ссылке. Описание ByRef используется в Visual Basic по умолчанию.

ParamArray — Необязательный. Используется только в качестве последнего элемента в списке списокАргументов для указания, что конечным аргументом является описанный как Optional массив значений типа Variant. Ключевое слово ParamArray позволяет задавать произвольное количество аргументов. Оно не может быть использовано со словами ByVal, ByRef или Optional.

имяПеременной — Обязательный. Имя переменной, удовлетворяющее стандартным правилам именования переменных.

тип — Необязательный. Тип данных аргумента, переданного в процедуру; поддерживаются типы Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (в настоящее время не поддерживается), Date, String (только строки переменной длины), Object, Variant. Если отсутствует ключевое слово Optional, могут быть также указаны определяемый пользователем тип или объектный тип.

поУмолчанию — Необязательный. Любая константа или выражение, дающее константу. Используется только вместе с параметром Optional. Если указан тип Object, единственным значением по умолчанию может быть значение Nothing.

Дополнительные сведения

Процедуры Sub, тип которых не указан явно с помощью слов Public или Private, являются

общими по умолчанию

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

Внимание! Допускаются рекурсивные процедуры Sub; т.е. они могут вызывать сами себя для выполнения определенных задач. Однако рекурсия может приводить к переполнению стека. Ключевое слово Static обычно не используется с рекурсивными процедурами Sub

Все выполняемые команды должны содержаться в процедурах. Не допускается определение процедуры Sub внутри другой процедуры Sub, Function или Property.

Инструкция Exit Sub приводит к немедленному выходу из процедуры Sub. Выполнение программы продолжается с инструкции, следующей за инструкцией, содержащей вызов процедуры Sub. В любом месте процедуры Sub допускается наличие любого числа инструкций Exit Sub.

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

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

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

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

Примечание. Для входа или выхода из процедуры Sub нельзя использовать инструкции GoSub, GoTo или Return.

Справка © Microsoft Excel 97

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

Содержание

  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, которая показывает пользователю всплывающее окно с предупреждением.

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

Понравилась статья? Поделить с друзьями:
  • Vba excel spinbutton пример
  • Vba excel replace пример
  • Vba excel sort key1
  • Vba excel replace in string
  • Vba excel soap запрос