Private sub vba что это
Перейти к содержимому

Private sub vba что это

Оператор Sub

Синтаксис оператора Sub состоит из следующих частей:

Part Описание
Public Необязательный элемент. Показывает, что процедура Sub доступна всем другим процедурам во всех модулях. При использовании в модуле, содержащем оператор Option Private, процедура становится недоступной вне проекта.
Private Необязательный элемент. Показывает, что процедура Sub доступна только другим процедурам из модуля, в котором она объявлена.
Friend Необязательный элемент. Используется только в модуле класса. Показывает, что процедура Sub видима по всему проекту, кроме контроллера экземпляра объекта.
Static Необязательный элемент. Показывает, что локальные переменные процедуры Sub сохраняются в промежутках между вызовами. Атрибут Static не влияет на переменные, объявленные вне процедуры Sub, даже если они используются в процедуре.
name Обязательно. Имя процедуры Sub массива; должен соответствовать стандартным правилам именования переменных.
arglist Необязательный элемент. Список переменных, представляющих аргументы, передаваемые в процедуру Sub при ее вызове. В качестве разделителя переменных используется запятая.
Операторы Необязательный элемент. Любая группа операторов, выполняющихся внутри процедуры Sub.

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

[ Необязательный ] [ ByVal | ByRef ] [ ParamArray ] varname [( ) ] [ Как тип ] [ = defaultvalue ]

Part Описание
Необязательное Необязательный элемент. Ключевое слово, которое указывает, что аргумент не является обязательным. При использовании все последующие аргументы в arglist также должны быть необязательными и объявляться с помощью ключевого слова Необязательный . Optional не может использоваться для каких-либо аргументов, если используется ParamArray.
ByVal Необязательный элемент. Указывает, что аргумент передается значением.
ByRef Необязательный элемент. Указывает, что аргумент передается по ссылке. ByRef является значением по умолчанию в Visual Basic.
ParamArray Необязательный элемент. Используется только в качестве последнего аргумента в arglist , чтобы указать, что последним аргументом является необязательный массив элементов Variant . Ключевое слово ParamArray позволяет предоставлять произвольное число аргументов. Ключевое слово ParamArray не может использоваться с аргументами ByVal, ByRef или Optional.
varname Обязательно. Имя переменной, представляющее аргумент; соответствует стандарту соглашений об именовании переменных.
тип Необязательный элемент. Тип данных аргумента, переданного процедуре; могут быть Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (не поддерживается в настоящее время), Date, String (только для переменной длины), Object, Variant или определенного типа объекта. Если параметр не является Optional, может быть указан определяемый пользователем тип.
defaultvalue Необязательный элемент. Любая константа или константное выражение. Действительно только для параметров Optional. Если типом является Object, явным значением по умолчанию может быть только Nothing.

Примечания

Если не указано явно с помощью общедоступных**,** частных или friend, процедуры Sub являются общедоступными по умолчанию.

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

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

Процедуры 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 для принудительного явного декларирования переменных.

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

Пример

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

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Sub statement

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[ Private | Public | Friend ] [ Static ] Sub name [ ( arglist ) ]
[ statements ]
[ Exit Sub ]
[ statements ]
End Sub

The Sub statement syntax has these parts:

Part Description
Public Optional. Indicates that the Sub procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.
Private Optional. Indicates that the Sub procedure is accessible only to other procedures in the module where it is declared.
Friend Optional. Used only in a class module. Indicates that the Sub procedure is visible throughout the project, but not visible to a controller of an instance of an object.
Static Optional. Indicates that the Sub procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Sub, even if they are used in the procedure.
name Required. Name of the Sub; follows standard variable naming conventions.
arglist Optional. List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.
statements Optional. Any group of statements to be executed within the Sub procedure.

The arglist argument has the following syntax and parts:

[ Optional ] [ ByVal | ByRef ] [ ParamArray ] varname [ ( ) ] [ As type ] [ = defaultvalue ]

Part Description
Optional Optional. Keyword indicating that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared by using the Optional keyword. Optional can’t be used for any argument if ParamArray is used.
ByVal Optional. Indicates that the argument is passed by value.
ByRef Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.
ParamArray Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. ParamArray can’t be used with ByVal, ByRef, or Optional.
varname Required. Name of the variable representing the argument; follows standard variable naming conventions.
type Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (variable-length only), Object, Variant, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks

If not explicitly specified by using Public, Private, or Friend, Sub procedures are public by default.

If Static isn’t used, the value of local variables is not preserved between calls.

The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure doesn’t appear in the type library of its parent class, nor can a Friend procedure be late bound.

Sub procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually is not used with recursive Sub procedures.

All executable code must be in procedures. You can’t define a Sub procedure inside another Sub, Function, or Property procedure.

The Exit Sub keywords cause an immediate exit from a Sub procedure. Program execution continues with the statement following the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can’t be used in an expression.

You call a Sub procedure by using the procedure name followed by the argument list. See the Call statement for specific information about how to call Sub procedures.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. To avoid this kind of conflict, explicitly declare variables. Use an Option Explicit statement to force explicit declaration of variables.

You can’t use GoSub, GoTo, or Return to enter or exit a Sub procedure.

Example

This example uses the Sub statement to define the name, arguments, and code that form the body of a Sub procedure.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

An Excel Blog For The Real World

A blog focused primarily on Microsoft Excel, PowerPoint, & Word with articles aimed to take your data analysis and spreadsheet skills to the next level. Learn anything from creating dashboards to automating tasks with VBA code!

TheSpreadsheetGuru

Explaining Private vs. Public Declarations

So What’s This Private and Public Stuff Mean?

The VBA terms Private and Public declare the access allowed to the term it’s attached to. Think of it in terms of a private company versus a public company. When trying to search for data on a private company you or I can’t really find much because only certain people have access to knowing their financials. Now if we wanted to know the depreciation expense of a company like Microsoft, we could find that in a split second because they are a public company and everyone has access to a public company’s financials. Keep this in mind as we dig into how VBA uses the terms Private and Public.

Private and Public are mostly used to either declare the scope of a variable or a subroutine (sub). You may also see the word “Dim” used to declare a variable. You can think of Dim as another way of stating Private; however there is a time and a place to use each one. I will touch on how to determine which word to use in the following sections.

What Does Private Mean?

Private Sub sets the scope so that subs in outside modules cannot call that particular subroutine. This means that a sub in Module 1 could not use the Call method to initiate a Private Sub in Module 2. (Note: If you start at the Application level, you can use Run to override this rule and access a Private Sub)

Private [insert variable name] means that the variable cannot be accessed or used by subroutines in other modules. In order to be used, these variables must be declared outside of a subroutine (usually at the very top of your module). You can use this type of variable when you have one subroutine generating a value and you want to pass that value on to another subroutine in the same module.

Dim [insert variable name] is used to state the scope inside of a subroutine (you cannot use Private in its place). Dim can be used either inside a subroutine or outside a subroutine (using it outside a subroutine would be the same as using Private).

What Does Public Mean?

Public Sub means that your subroutine can be called or triggered by other subs in different modules. Public is the default scope for all subs so you do not need to add it before the word “sub”. However, it does provide further clarity to others who may be reading your code. As a personal preference I do not type Public Sub unless I am creating an intricate program that has a bunch of subroutines with varying scopes (ie I have a mix of Public & Private subs).

Public [insert variable name] means that the variable can be accessed or used by subroutines in outside modules. These variables must be declared outside of a subroutine (usually at the very top of your module). You can use this type of variable when you have one subroutine generating a value and you want to pass that value on to another subroutine stored in a separate module.

Putting It All Together

Let’s look at an example of how Public and Private scopes interact with each other. For this example let’s presume that we insert two modules into a new workbook and place the below code in their respective module.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *