LEGAL VS. ILLEGAL VARIABLE DECLARATIONS

 

The figure below attempts to highlight concepts of variable declaration and scoping discussed previously:

 

PROJECT

(Form1)

Option Explicit

 

'General Declarations Section ...

 

Public  intA As Integer

Private intB As Integer

 

Private Sub MySub1()

 

    Dim intC As Integer

 

    intC = intA  'OK – intA is public (declared in this form)

    intC = intW  'OK – intW is public (declared in Module1)

    intC = intB  'OK – intB is a module-level variable of this form

    intC = intD  'Error – intD is local to MySub2

    intC = intX  'Error – intX is private to Module1

 

End Sub

 

 

Private Sub MySub2()

 

   Dim intD As Integer

 

   intD = intA  'OK – intA is public (declared in this form)

   intD = intW  'OK – intW is public (declared in Module1)

   intD = intB  'OK – intB is a module-level variable of this form

   intD = intC  'Error – intC is local to MySub1

   intD = intX  'Error – intX is private to Module1

 

End Sub

 

 (Module1)

Option Explicit

 

'General Declarations Section ...

Public  intW As Integer

Private intX As Integer

 

Public Sub MySub3()

 

    Dim intY As Integer

 

    intY = intA         'Error – qualification required

    intY = Form1.intA   'OK – intA is public (declared in Form1)

    intY = intW         'OK – intW is public (declared in this module)

    intY = intX         'OK – intX is a module-level variable of this module

    intY = intZ         'Error – intZ is local to MySub4 

    intY = intB         'Error – intB is private to Form1

    intY = Form1.intB   'Ditto

 

End Sub

 

 

Public Sub MySub4()

 

    Dim intZ As Integer

 

    intZ = intA        'Error – qualification required

    intZ = Form1.intA  'OK – intA is public (declared in Form1)

    intZ = intW        'OK – intW is public (declared in this module)

    intZ = intX        'OK – intX is a module-level variable of this module

    intZ = intY        'Error – intY is local to MySub3

    intZ = intB        'Error – intB is private to Form1

    intZ = Form1.intB  'Ditto

 

End Sub