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 :/
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
myVarwithintryand pass it as a parameter todisplayVar. This preventsdisplayVarfrom accidentally changingmyVarbecause, 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
Publicmeans these subroutines are visible to subroutines in other modules. IfPublicwas omitted or replaced byPrivate,tryanddisplayVarwould only be visible within their module.In the code below I have passed the value of
myVaras a parameter todisplayVar.