What does Public really do?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have this at the beginning of my code:
Public intPhoneErrorCount As Integer
....I make it Public so that I can access that integer from different
Functions that are called. This variable doesn't clear itself after my code
is finished running, though. ...if I run the code again, this variable (a
counter) picks up from where it left off the last time I ran the code. Is
this supposed to be? Can I change this so it doesn't have this 'memory'?
thanks,
ck
 
Charlie said:
I have this at the beginning of my code:
Public intPhoneErrorCount As Integer
...I make it Public so that I can access that integer from different
Functions that are called. This variable doesn't clear itself after my code
is finished running, though. ...if I run the code again, this variable (a
counter) picks up from where it left off the last time I ran the code. Is
this supposed to be? Can I change this so it doesn't have this 'memory'?


That is generally considered as a weak approach to sharing a
value.

It would be better if you could arrange your procedures to
pass the value as an argument. Then the top most procedure
could declare the variable lacally.

If you really need a global (Public) variable, you would be
better off using a text box on an always open form. This is
because any unhandled error will reset all standard module
public variables, which can play wreak havoc while you are
debugging.

To answer your specific question, your procedure should set
the variable to 0 before the code that does the counting.
 
Another alternative is to use a public function with a static variable is a
standard module. It does not suffer from the value reset problem because the
value is local to the function. If the function receives a value, it stores
it in the static variable and returns it. If it receives no value, it
returns the last value it received.

Public Function SaveThisValue(varValue As Variant) As Variant
Static varSave As Variant

If Not IsMissing(varValue) Then
varSave = varValue
End If
SaveThisValue = varSave
End Function
 
Back
Top