Scope of Variable

     

    Click on below mentioned image to watch the video:

     

    Download The Workbook

     

  • Scope represents LIFE TIME\ACCESSIBILITY of Variable
  • It indicates where it is available
  • We can declare variables at 3 levels
  •  

    • Procedure Level
    • Module Level
    • Project Level

     

    Declaration of Variable - PROCEDURE Level

     

  • This Variable must be between Sub - - - End Sub
  • This also termed as LOCAL VARIABLE
  • Local variable doesn't exists after END SUB(end of the code)
  • i.e., it is accessible within the function\procedure
  • We can use DIM,PRIVATE,STATIC to declare variable
  •  

    Example:

     

     

    Declaration of Variable - MODULE Level

     

  • Declaration of variable at MODULE level, enables to use the variable in all the procedures available the MODULE Sheet
  •  

  • We can use Module level variable against the all the procedures WITHIN THE MODULE
  •  

  • A variable that is available against the all the procedures within the MODULE sheet termed as MODULE LEVEL variable
  •  

  • We need to declare varible at the TOP of the module, it is available to all procedures within the module
  •  

  • We can create with DIM and PRIVATE Statements
  •  

  • Variable lost its scope on use of END SUB or when we close the work book
  •  

  • We shouldn't declare Module level variables within the procedure
  •  

  • In general DIM is used at PROCEDURE LEVEL variables, and PRIVATE is used for MODULE LEVEL variable., but it depends entirely on our choice. Both statements represents same
  • Example:

     

     

    Declaration of Variable - PROJECT Level

     

  • This variable is available for all the MODULES in Active Workbook
  •  

  • We can declare PUBLIC variable in any MODULE
  •  

  • It is declared at TOP of the MODULE
  •  

  • It is declared with PUBLIC statement
  •  

  • Variable shouldn't declare within PROCEDURE
  •  

  • This variable available to all procedures and all variables
  •  

  • Variable destroyed at END SUB or WORK BOOK is closed
  •  

     

    Example:

     

    What is the difference between Dim,private,Public

     

    • DIM & PRIVATE both are same
    •  

    • Global can be used at standard modules where as PUBLIC can be used in all contexts(modules,classes,controls,forms)
    •  

    • Global can be used in older version of VB, now it replaced with PUBLIC
    •  

    • PUBLIC is available in all modules in all forms,controls...

     

    Constant Variable

     

  • This is constant variable, once defined never change
  •  

    Private Sub CommandButton1_Click()
    'path is fixed
    Const pathname = "c:\users"
    MsgBox pathname
    End Sub

     

     

    Private Sub CommandButton1_Click()
    Const mont As Integer = 12
    Dim permonth As Integer
    permonth = 12000 / mont
    MsgBox permonth
    End Sub