Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

When to Dim, Private or Public

Status
Not open for further replies.

newboy18

MIS
Apr 11, 2003
45
GB
Please help, I am getting a bit confused.
If I want a variable to be only available in the current Sub routine then I use Dim, If I want the variable to be available in all Modules then I use Public.
Does it matter if I make the statement is before or after the beginning of the Sub routine?
What should I do if I want the variable to be available to the current Module only?
The problem started when I found that a variable that had been dimmed in 1 module was available in another Module but the value was not.
 
Newboy18,

In order for a variable to be available to the entire application, it must be declared at the top of a module as public, ideally before the start of the first sub or function.

If you want it to be available to the current module only, use Dim at the top of the module.

I should point out however, that using shared or global variables is considered poor programming practise because it is easy for a code to change the data used elsewhere with no method of stopping this. Instead, the preferred method is to pass the value of the data in as a parameter of the function, something like
Code:
Public Function FunctionName (Parameter As String) As Integer

If Parameter = "fred" then FunctionName = 10 Else FunctionName = 20

End Function

You can then call it as

Result = FunctionName (strStringvariable)

John
 
Thanks John,
So if I put the Dim after the start of the Sub routine then it will only be available in that Sub routine, if I put it before the start of the Sub routine then it will be available to all Sub routines in this Module and if I make it Public then it will be available to all Modules
 
Newboy
Yes, you have got it exactly right.
This determination of how visible and accessibility of a variable is called variable scope, and is something that any programmer has to get to grips with.

John
 
The "Public" and "Private" prefixes can also be applied to functions and subroutines (note that by default, event handlers start "Private Sub "
This means that they are only available within that particular module.

A public sub or function is available anywhere. If this prefix is omitted, I think it is assumed to be public in an ordinary module or private in a form or report module.

John
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top