Search code examples
vb.netvariablesvbascoping

Type of variable scoping in vba language


I try to understand the VBA scope type, it's impossible to make this such of thing in VBA, but it's possible in other language (java,scala,etc):

public sub try()

    dim myVar as String
    myvar = "hello world" 

    Call displayVar()

end sub

public sub displayVar()
   msgbox (myvar)
end sub

Can you give me some information about this type of limited scoping ? It's dynamical or lexical, i don't really understand the difference :/


Solution

  • Franck Leveque has provided a clear and simple demonstratation of the difference between local and global declarations.

    However, like most languages, VBA allows you to pass parameters to subroutines. Sometimes a global variable is the only choice or the only sensible choice. But normally it it is better to declare myVar within try and pass it as a parameter to displayVar. This prevents displayVar from accidentally changing myVar because, by default, parameters are passed as values. If you want a subroutine to change the value of a parameter you must explicitly pass the parameter as a reference. This is true of most modern programming languages.

    Note also that Public means these subroutines are visible to subroutines in other modules. If Public was omitted or replaced by Private, try and displayVar would only be visible within their module.

    In the code below I have passed the value of myVar as a parameter to displayVar.

    Public Sub try()
    
      Dim myVar As String
    
      myvar = "hello world"
      Call displayVar(myVar)
    
    End Sub
    
    Public Sub displayVar(Stg As String)
      Call Msgbox(Stg, VBOKOnly)
    End Sub