Setting up VB variables

User avatar
silverback
5StarLounger
Posts: 776
Joined: 29 Jan 2010, 13:30

Setting up VB variables

Post by silverback »

I know that if I declare variables at the beginning of a Visual Basic module, the variables are usable by any sub or function in that module. I want to declare what are, in effect, constants for that module, instead of having to assign values to the variable in the subs which use them i.e something equivalent to

Dim intItem1 as Integer
intItem1 = 1
but at the module level.

How do I do this, please?
Thanks
Silverback

User avatar
HansV
Administrator
Posts: 78523
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Setting up VB variables

Post by HansV »

If you want them to be constant, declare them as constant at the top of the module:

Const intItem = 1

You won't be able to change the value of a constant in your procedures or functions.

By the way, a constant declared this way is only available within the module that contains it. If you want it to be available in all modules, prefix the declaration with Public:

Public Const intItem = 1

Also see A Dim understanding: declaring variables in VB/VBA.
Last edited by HansV on 30 Jul 2010, 13:04, edited 1 time in total.
Reason: to correct stupid error
Best wishes,
Hans

User avatar
silverback
5StarLounger
Posts: 776
Joined: 29 Jan 2010, 13:30

Re: Setting up VB variables

Post by silverback »

As always, my grateful thanks.
Silverback

User avatar
silverback
5StarLounger
Posts: 776
Joined: 29 Jan 2010, 13:30

Re: Setting up VB variables

Post by silverback »

HansV wrote:If you want them to be constant, declare them as constant at the top of the module:
Constant intItem = 1
You won't be able to change the value of a constant in your procedures or functions.
Onviously doing something wrong. I have this code at the beginning of the module.

Code: Select all

Option Compare Database
Option Explicit

Constant intOpt = 0
Constant intType = 1
Constant intValQ = 2
Constant intExtQ = 3
Constant intEOID = 5

Dim strWhereClause As String, strEOID As String
but it generates an error Invalid Outside Procedure. Can you help again, please?
Thanks
Silverback

User avatar
HansV
Administrator
Posts: 78523
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Setting up VB variables

Post by HansV »

Sorry, my bad! :blush:

The keyword to declare a constant is Const, not Constant, so for example

Const intOpt = 0

I have corrected my previous reply.
Best wishes,
Hans