Jack Leach said:
Marshall Barton said:
[...] I also like David Fenton's often posted
approach that takes it to yet another level by making it
read only and self healing after a reset.
Public Function MyVar()
Static X As Variant
If IsNull(X) Then X = {something}
MyVar = X
End Function
Yes, this is good. I tend to do something similar using a public Property
Get with a private Let. But with David's method the static can be
declared
at procedure level rather than module level, and the work can be condensed
into a single procedure. A bit more elegant, I think.
If one will go through the trouble to make sure to only use public values
for app-level data, then it would make sense to take this further step to
secure them a little better.
At that point, we can say that "public variables" are pretty much useless
in
VBA...
I agree, but twas not always like that. VB Classic (vb6) didn't suffer with
global variable frailty like VBA, yet VBA evolved from vb6. Interesting that
the move from compileable code to just p-code interpretation seems to be at
the heart of the issue. Running VBA code is like running vb6 code in the
debug environment (p-code), but even then vb6 didn't break globals when an
unhandled error occurred. MS *must* have received complaints about this over
the years, yet they've never fixed it. That leads me to suspect that they
*can't* fix it for some reason. Maybe MichKa could tell us if he were still
around on here.
One method I use to circumvent this bug (yes it is a bug IMO) is to use ini
files. "Oh but that's doing a disk fetch" you might say, but once an ini
file has been accessed for the first time, it resides in the file system's
cache, so subsequent values are in fact read from RAM and are just as quick
and efficient as globals, but without the frailty. And their values survive
an application (or even a computer) reset.
.