All Snippets
Top 100 Snippets

By Language

GBIC >> Source Code >> Visual Basic >> Snippet

11 Scope

'Scope  -------------------------------------------------------------------------------

'The scope of a variable defines which parts of your program are aware of
'the variable.  When you declare a variable within a procedure (sub/function)
'only code within that procedure can access or change the value of that variable.
'The variable's scope is local to the procedure.

'Scope of a variable can be controlled by the programmer.  Variables are
'declared in one of two locations - procedures or modules.  In each case,
'VB allows the declaration to define the procedure as Private or Public:

'Procedure-level variables
  Private   'variables are private to the procedure
  Public   'n/a.  procedure variables cannot be Public
'Module-level variables
  Private   'variables are private to the module
   'they can be accessed from within any procedure in the module
  Public   'variables are available to all modules

'Example:  to make a public variable, put this in the declaration section of a module
'Note:  Public replaces Dim in the declaration

Public MyVar As Long

'Example: to make the same variable private to the module, use this:

Private MyVar As Long

'Lifetime  -------------------------------------------------------------------------------

'Normally, when a variable is declared in a procedure (sub/function) it exists only as long
'as the procedure is executing.  For example:

Sub MySub ()
    Dim j As Long
   j = 5
End Sub

'When the program call MySub, the variable j is created.  When the program exits
'MySub the variable i no longer exists.

'The exception is that if the declaration uses the keyword Static, the variable continues
'to exist between calls of the procedure:

Sub MySub()
    Static Dim j As Long
   i = j + 5
End Sub

'In this example, the value of j is kept.  Each time the procedure is called, j is incremented
'by an additional 5.

'These comments apply to module variables also