Public Const String = «Строка»
т.е. не так, а так:
Public Const Stroka as String = «Строка»
Public Const String = «Строка»
т.е. не так, а так:
Public Const Stroka as String = «Строка» Анатолий
Сообщение Public Const String = «Строка»
т.е. не так, а так:
Public Const Stroka as String = «Строка» Автор — Анатолий
Дата добавления — 05.02.2014 в 09:57
Источник
VBA Declare Constant with Const and Public Const
The VBA Tutorials Blog
You should declare constants in your VBA project when you need a value defined and you know the value won’t change. I often find myself using VBA constants when working with scientific equations. To declare constants, you use the VBA Const and Public Const statements. Recall that you typically declare variables using Dim statements, instead.
Unlike variables, you can’t change the value of a VBA constant once it’s declared. This tutorial will show you how to declare constants and will explain the difference in scope between a constant declared using a Const statement and one declared using a Public Const statement.
Declaring Constants with VBA
There are 3 ways to declare a constant in VBA. Each method has a different scope. The first method only makes the constant available in the procedure (subroutine or function) where it’s declared. These are called procedure level constants.
The second method lets you access the constant from any procedure within a single module. That’s why these constants are called module level constants.
The final method makes the constant available in all modules and procedures in your entire workbook. Constants with this highest level of scope are called project level constants.
Let’s explore these three options now.
Procedure Level Constants with VBA Const
Procedure level constants in VBA are declared inside your procedure using the Const keyword. The general syntax is Const Name as Type = Value where Name is the name of your constant, Type is the data type you want to declare and Value is the value you want to assign to the constant. Let’s walk through an example.
In this example, we declare a constant, Gravity , representing the constant acceleration of gravity as 9.80665 m/s 2 . Notice the placement of the Const declaration. It’s inside the procedure. By declaring the constant inside our Force_Gravity routine, we’re making it so the value stored in Gravity cannot be accessed in any other routine.
Make powerful macros with our free VBA Developer Kit
It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.
If you try to reference the Gravity constant from another subroutine or function, even one located inside the same module, it won’t have a value. That means you’re allowed to define multiple procedure level constants with the same name and different values as long as they’re in different procedures. Take this code, for example:
Even though both constants are named color , you’re able to store different strings in them because they’re both procedure level constants. They only retain their value inside the procedure they were created in.
Module Level Constants with VBA Const
The syntax for a module level constant is the same as a procedure level constant, but the placement of the declaration changes. Module level constants are accessible in any subroutine or function in your module. Here’s a good example illustrating how to declare a module level constant:
Notice the Const declaration was placed at the top of your module. It’s declared outside of any subroutine or function. This is the key for module level constants. Declarations must be made at the top of your module and must not be inside a procedure. Once you do that, you can access the constant from any procedure (subroutine or function) in that module.
In this example, we used Einstein’s famous E=mc 2 special relativity formula to calculate the energy of an object with two different masses. We succesfully referenced the speed of light constant, c , in both subroutines.
You can start to see the appeal of using constants with this example. You don’t want to accidentally change the value of c when accessing it in different procedures! That’s the risk you’d run into if you had declared it as a variable.
Project Level Constants with VBA Public Const
Project level constants can be accessed by any subroutine or function inside your workbook, even if they’re in different modules. This is going to be a fun scientific example so stick with me. Let’s say you have a module named mMassEnergy and a module named mWavelengthEnergy . You can see both of our modules in this screenshot from our Project Explorer Pane.
In the mMassEnergy module, you’ll declare a project level constant using the Public Const declaration. This module will allow you to calculate the energy of an object based on its mass.
The Public keyword is the secret to making your constants usable across multiple modules.
Our second module, mWavelengthEnergy , will use the speed of light public constant, c , but it will calculate the energy of light given its wavelength using the Planck-Einstein equation, E=hv . Unlike the module level constant, c , the Planck constant, h , is declared as a procedure level constant, so it can only be used within the mWavelengthEnergy module.
Even though we never defined the speed of light constant, c , in this module, our subroutine successfully calculates the energy as 3.78370639456939E-19 Joules. It’s able to do this with the help of our Public Const declaration in our mMassEnergy module.
On a related note, the code above illustrates how you can use formulas to define constants, as long as your formulas don’t contain any variables.
Common Errors with Constants
This section covers a couple common issues people encounter when working with VBA constants. Read it carefully to avoid making the same errors on your project.
Initializing Constants
Unlike variables, you must set a constant equal to a value when declaring it. If you don’t set your constant to a value using the equal sign during your declaration, the declaration line will turn red and you’ll get a compile error reminding you the code was expecting an equal (=) sign:
Reassigning Constants
Once a constant is declared in VBA, you cannot change its value. If you try to change the value stored in a constant, you’ll get a compile error stating “assignment to constant not permitted.”
Overwriting Constants (Precedence)
We just got done saying once a constant is declared in VBA, you can’t change its value. While that’s true, it’s worth noting that even module and project level constants can be overwritten by procedure level constants. For example:
Even though we already have a module level constant, MyColor , defined with a constant value of “Red”, the Color_test1 macro declares a new constant with the same name. It doesn’t treat this as a duplicate declaration. Instead of generating an “ambiguous name detected” error, when you run this macro, “Yellow” is printed to the VBA Immediate Window.
If you were to run the Color_test2 macro, though, it would print the value stored in the module level MyColor constant (“Red”).
Similar behavior exists with project level constants assuming you had a Public Const declaration in a separate module. Basically, procedure level constants take precedence over all other constants and module level constants take precedence over project level constants. Another way to think about this is the closer you are to your subroutine or function, the more power your constant declaration has (procedure > module > project).
Public Constants in Object Modules
Unfortunately, you’re not allowed to declare public constants inside object modules, like ThisWorkbook or Sheet1 . For example, let’s say you’re working on a VBA project in Excel. Trying to declare a Public Const inside any object module listed under the “Microsoft Excel Objects” group in your Project Explorer will create the following compile error:
We’ve used a couple scientific equations to illustrate when you might find it beneficial to declare constants in your VBA project. We showed you the difference between Const and Public Const and how placing your constant declarations in different spots can impact how you’re able to use your constants. We also explained a couple common errors people encounter when working with constants, including how once a constant is assigned a value, you cannot change it’s value later. That’s what variables are for!
I hope you found this tutorial helpful. If you haven’t already done so, please subscribe to our free wellsrPRO VBA Training using the form below and share this article on Twitter and Facebook.
Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.
Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.
Источник
Adblock
detector
Home / VBA / VBA Constants
What is a Constant in VBA?
In VBA, a constant is a storage box that is itself stored in your system and it can store a value in it for you, but the value which you assign to it cannot be changed during the execution of the code. In VBA there are two different kinds of constants that you can use:
- Intrinsic Constants
- User-Defined Constants
Intrinsic constants are those which are built into the VBA language itself (for example, the built-in constant vbOKCancel which you use in the message box), and on the other hand, user-defined constants are those which you can create by assigning a value to it.
Declare a Constant in VBA
- Use the keyword “Const”.
- Specify a name for the constant.
- Use the keyword “As” after the name.
- Specify the “Data Type” for the constant according to the value you want to assign to it.
- Equals to “=” sign.
- In the end, the value you want to assign to it.
Above is a constant that stores a birthdate. Now if you think, a birth date is something that is supposed to be fixed and for this kind of value, you can use a constant.
Scope of a Constant
Constant has the same scope as variables. When you declare a constant, it has a procedure-level scope, which means you can use it anywhere within the procedure. But you can declare a constant using a private or public scope.
A private constant is available only to the procedure where it is declared as a constant. To declare a private constant, you need to use the keywords “Private”, just like the following example.
Private Const iName As String = “Puneet”
And in the same way, you need to use the keyword “Public” when you need to declare a constant as public.
Public Const iPrice As String = “$3.99”
Return to VBA Code Examples
In this Article
- What is a Constant
- Data Types used by Constants
- Declaring a Constant within a Procedure
- Declaring a Constant within a Module
- Declaring Constants at a Global Level
This tutorial will demonstrate the use of VBA Constants.
A constant is similar to a variable and is declared in a similar way. There is, however, a major difference between them!
What is a Constant
A constant is a value that we declare in our code and consequently it is reserved in our computer’s memory and stored. We have to name our constant and it’s good practice to declare the data type of our constant. When we declare the data type, we are telling the program what type of data needs to be stored by our constant .
We will use the constant in our code, and the program will also access our constant. Unlike a variable, where the actual value can change while the code is running, a constant value never changes.
Data Types used by Constants
Constants use the same data type as Variables. The most common data types for Constants are as follows:
• String – this is used to store text values.
• Boolean – this is used to store TRUE or FALSE values.
• Integer – this is used to store whole number values.
• Double – this is used to store numbers with decimals.
• Date – this is used to store dates.
To see a complete list of all data types used by Variables and Constants in VBA, click here.
In VBA, we have to use a Const statement in order to declare a Constant. We can declare constants in a similar way to declaring Variables – at Procedure Level, at Module Level and at a Global Level.
Declaring a Constant within a Procedure
To declare a Constant at Procedure level, we declare it inside the procedure.
Sub CompanyDetails()
Const strCompany As String = "ABC Suppliers"
Const strAddress As String = "213 Oak Lane, Highgate"
MsgBox strCompany & vbCrLf & strAddress
End Sub
When we run the code, the message box will return the constant values.
Because the Constant is declared at Procedure level, we can declare a Constant with the same name in a different Procedure.
If we run the second Procedure, the Constant value stored in that Procedure is returned.
Declaring a Constant within a Module
If we want a Constant value to be available to all Procedures within a Module, we need to declare the constant at Module level.
This will make the same constant available to multiple procedures WITHIN that module only.
Should you use the Constant in a different module, an error will occur.
Declaring Constants at a Global Level
You can declare Constants at a Global Level which would then mean you can use them in all the Modules contained in your entire VBA Project.
To declare a Constant as a Global Constant, we need to put the word PUBLIC in front of the declaration statement.
For example:
Public Const strCompany as string = "ABC Suppliers"
This will allow the Constant to be used in all the modules regardless of where is is declared.
NOTE: you can ONLY declare a public constant at a Module level, you CANNOT declare a public constant within a procedure.
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!
Learn More!
peat Пользователь Сообщений: 119 |
#1 30.04.2013 18:35:30 Доброго времени суток! Надеюсь на вашу помощь)
Srok глобально объявлен как целое,
проблем с вызовом в каждой процедуре не было, но в каждую приходится писать эти вот строчки. Хотелось бы в сааааамом начале проекта его вычислить и вставлять по ходу действа, когда нужен. С другой переменной, тоже задающейся в самом начале, попробовал такую вот штуку:
заругалась «constant expression required». Найденные в сети варианты с Set… тоже успехом не увенчались. у меня вся эта байда во вкладке «Modules», где у меня описание всех кнопок, функции и тп. Мб куда в другое место надо перенести объявление глобальных переменных/констант? |
||||||
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
Где у Вас объявлены глобальные переменные? Нужно в области деклараций стандартного модуля. Т.е. ПЕРЕД ними не должно никаких процедур. А значения им присваивайте в процедуре, которая выполняется самой первой. |
peat Пользователь Сообщений: 119 |
#3 30.04.2013 19:20:58 Юрий М, на самом верху, да:
перед ними ничего нет. Если в первой процедуре Srok получит значение 100500, то при любых дальнейших вызовов этой переменной, ее значение будет равно 100500? Изменено: peat — 30.04.2013 19:24:41 |
||
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
Если затем это значение (100500) не менялось, то оно так и останется таким. И переменная будет доступна в любом модуле. |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
#5 30.04.2013 19:34:03 Вынесите присвоение переменным значений в отдельную процедуру(скажем InitPublic). Затем при открытии книги запускайте эту процедуру:
Так же на всякий случай в каждой процедуре, в которой переменная может понадобиться, можно делать проверку:
Так же можете почитать про переменные: Что такое переменная и как правильно её объявить? А то Вы их объявляете неверно(Юрий уже указал Вам на это). Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
Hugo Пользователь Сообщений: 23251 |
Ну и вместо integer пишите Long — оно оправданнее в новых версиях VBA, и кроме того у Вас с integer не будет работать на весь лист (ругнётся на LastRow (As Integer)). |
peat Пользователь Сообщений: 119 |
Юрий М, The_Prist, Hugo, спасибо Вам всем большое! ценные советы не знающим vba) |
peat Пользователь Сообщений: 119 |
#8 01.05.2013 01:10:30 The_Prist, сделал, как вы описали. Весь код в модулях прекрасно понимает глобальную переменную, но вот код в юзер форме отказывается это делать.
При дебагере эта процедура вызывается, но Srok все равно empty после прохождения. Изменено: peat — 01.05.2013 01:11:07 |
||
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
А что у Вас в процедуре InitPublic? Где она? И может есть смысл показать небольшой файл, где всё это происходит? |
peat Пользователь Сообщений: 119 |
#10 01.05.2013 01:45:56 Юрий М, видимо, она не там… Она в самом верху модуля, в котором бОльшая часть кода.
Вероятно, она не там висит. Если не в этом дело, накрамсаю файл для примера. |
||
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
И процедура InitPublic в модуле книги на событие открытия? Давайте лучше небольшой пример… |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
InitPublic должна быть расположена в стандартном модуле. Так же как и объявление Public переменных. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
нашел проблему — у меня не один стандартный модуль. При удалении других модулей глобальная переменная Srok спокойно работает в юзерформе. Надо создать какой-то другой модуль? читал по вашей ссылке про модуи классов — мне туда? Изменено: peat — 01.05.2013 11:48:49 |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
peat, Вы считаете необходимым пустое сообщение писать? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
#15 01.05.2013 11:59:38 The_Prist, нет, просто надо было его удалить — не нашел кнопки) попробовал создать модуль класса, запихнул туда
не помогло — в юзер форме Srok = empty, если call InitPublic — то не находит ее.. |
||
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
Необходимо поместить в один стандартный модуль — ЛЮБОЙ. СТАНДАРТНЫЙ. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
конечно, сам создал) но с вашей помощь сам и решил — в другом модуле эта же переменная тоже объявлялась, как паблик, в этом проблема и была)еще раз спасибо |
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
Не понимаю — почему люди так упорно не желают показывать файлы-примеры?.. Давно бы получили правильный ответ. |
peat Пользователь Сообщений: 119 |
у меня достаточно большой файл, в нем много кода. он не сложный, никуда не претендует, но его много) надо бОльшую часть удалить, чтобы не мешала поиску проблему — лениво немного) и выкладывать как-то стремновато — диплом все ж таки) хотя пока подготавливал файл к выкладыванию, нашел ошибку) |
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
#20 01.05.2013 13:08:47
Вам лениво готовить небольшой файл, а нам не лениво искать Вашу ошибку по описанию? С таким подходом помогающих у Вас поубавится… |
||
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
На мой взгляд это как раз тот случай, когда размер не имеет значения Ошибка-то явно в объявлении, а не в самих кодах. Поэтому даже большой проект можно просмотреть бегло только в нужных местах, не ковыряясь в кодах. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
#22 01.05.2013 14:04:23 The_Prist, да вот именно, что я не один раз объявлял ее в этих самых кодах и, чистя их, нашел понял в чем ошибка)
мне казалось, скачивать файл еще муторней) В итоге, Вы и помогли по описанию |
||
sm_ph Пользователь Сообщений: 1 |
#23 26.06.2019 13:49:50 У меня работает так:
Изменено: sm_ph — 26.06.2019 13:51:44 |
||
The Pi’s value is 3.14, the gravitation pull of the Earth is 9.8 m/s2, you have an interest in VBA, etc. These all are constants and they don’t change.
In VBA you can define variables whose value can’t be changed in the program. The VBA programmer defines these constant values by themselves in the program to use them again and again.
How to Define a Constant Value in VBA?
We use the keyword Const to declare a constant in VBA.
The syntax of declaring a constant variable in VBA is:
[<Scope Specifier>] Const <VarName> as <variable_type> = <value>
[<Scope Specifier>]: The scope specifier is optional. You specify the scope of the constant (public or private) if you want, otherwise don’t declare it. By default, the scope of a constant is private. You can read about Scope Specifiers here.
Note: We never use the Dim keyword to declare a constant in VBA.
<VarName>: It is the name of the constant variable.
<variable_type>: The type of the constant. For example, Integer, String, Date, etc.
<value>: The value of the constant variable.
A simple example of the Constant Variable is:
Const pi as double = 3.14
Here we declared the constant value of pi in a variable named pi. Now we can use this pi in our program. The value will always be 3.14. If you try to change the value of a constant variable, the Excel VBA will pop up an error message.
VBA Constant Variable Examples
Study the below code:
Const pi As Double = 3.14 Const rad As Double = 6371 Sub Earth() sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub Sub Mars() rad = 3389.5 sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub
Here, we have defined two constants, pi, and the rad. The pi’s value is 3.14 and rad is 6371 which is the earth’s radius.
Now, when we run the first sub the Earth, it works perfectly fine and prints the surface area of the Earth.
In the next sub-Mars, we redefined the constant rad as the radius of mars is different. When we run this program, it throws an error saying, «Assignment to constant is not permitted«.
How to reinitialize a constant in VBA
As you have seen in the above example that we can’t assign new values to a constant. Yes, you can’t.
But if you still need to use the same name as a different fixed value, just use the Const keyword before the assignment.
The below code will work perfectly.
Const pi As Double = 3.14 Const rad As Double = 6371 Sub Earth() sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub Sub Mars() Const rad = 3389.5 sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub
The above subroutine will work perfectly without any errors. But I don’t recommend this approach. The best way is to identify the public and private constants and define them separately. And this brings us to our next segment.
Public and Private Constants in VBA
As we learned in the above examples, some constants may be universal and some may differ for different objects. Like, the pi value is constant for the entire universe, but the number of planets very solar system to solar system and radius of planets varies planet to planet.
As the Earth’s radius is constant for it, not for the universe. Similarly, in programs, there will be some constants will be private to sub’s and module’s and some will be public constant for the entire VBA project. Your job is to identify them and declare them differently.
Let’s take another example:
Public Const pi As Double = 3.14 ' This can be accessed from any module in the project Private Const planets As Integer = 8 ' this is private to this module Sub Earth() Const rad As Double = 6371 'Private to this subroutine. Can't be accessed outside sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub Sub Mars() Const rad As Double = 3389.5 'Private to this subroutine. Can't be accessed outside sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub
This is a simple variable scope specifying. You can read about the variable scope setting here in detail.
So yeah guys, this is how you declare and use constants in Excel VBA. I tried to explain in a creative way. I hope I was explanatory enough. If you have any doubt, ask in the comments section below. I will be happy to hear and reply to you.
Related Articles:
Excel VBA Variable Scope | we have variable access specifiers that define from where a defined variable can be accessed. Excel VBA is no Exception. VBA too has scope specifiers. These scope specifiers can be used to set the visibility/scope of a variable in Excel VBA.
ByRef and ByVal Arguments |When an argument is passed as a ByRef argument to a different sub or function, the reference of the actual variable is sent. Any changes made into the copy of the variable, will reflect in original argument.
Delete sheets without confirmation prompts using VBA in Microsoft Excel|Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.
Add And Save New Workbook Using VBA In Microsoft Excel 2016|In this code, we first created a reference to a workbook object. And then we initialized it with a new workbook object. The benefit of this approach is that you can do operations on this new workbook easily. Like saving, closing, deleting, etc
Display A Message On The Excel VBA Status Bar The status bar in excel can be used as a code monitor. When your VBA code is lengthy and you do several tasks using VBA, you often disable the screen update so that you don’t see that screen flickering
Turn Off Warning Messages Using VBA In Microsoft Excel 2016|This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.
Popular Articles:
50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.
The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets.
COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific value. Countif function is essential to prepare your dashboard.
How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.