ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Life of a variable (https://www.excelbanter.com/excel-programming/291999-life-variable.html)

Mike Fogleman

Life of a variable
 
I have a huge amount of code, over 80 subs, spread over 4 general modules,
with a userform and workbook open & close. Most variables are keeping their
last value when the routine has ended. When I run the routine again, on
different data, the results are not correct. Re-running the routine
immediately on this data works.

2 questions: VB help says a variable will retain its' scope when calling one
sub from another. I have found that if the called sub is in another module,
scope is lost. Is this normal? Declaring the variable Public in the
originating module works, so I have a lot of Public variables to keep the
code running as it criss-crosses the 4 modules.

Second, is there a global way to reset the variables between runs, like the
Reset button on the VB Editor?
TIA, Mike



Tom Ogilvy

Life of a variable
 
Except for Public variables declared at the top of general modules, a
variables scope is limited to the procedure in which it is declared. You
can pass a variable in the argument list of procedure (either byref or
byval). If byval, think of it as being local to that procedure (it is just
initialized by the calling procedure). If byref, then the variable is
visible to both procedures until the called procedure returns control back
to the calling procedure. Once code stops running, the only variables
retaining there values would be public variables - think of them as being
"local" to the workbook/project - so as long as that is running, they retain
their values unless you take action (such as reset) to change them.

The only generalized command that will clear all variables is the END
statement, but it also halts code immediately.

--
Regards,
Tom Ogilvy

"Mike Fogleman" wrote in message
...
I have a huge amount of code, over 80 subs, spread over 4 general modules,
with a userform and workbook open & close. Most variables are keeping

their
last value when the routine has ended. When I run the routine again, on
different data, the results are not correct. Re-running the routine
immediately on this data works.

2 questions: VB help says a variable will retain its' scope when calling

one
sub from another. I have found that if the called sub is in another

module,
scope is lost. Is this normal? Declaring the variable Public in the
originating module works, so I have a lot of Public variables to keep the
code running as it criss-crosses the 4 modules.

Second, is there a global way to reset the variables between runs, like

the
Reset button on the VB Editor?
TIA, Mike






All times are GMT +1. The time now is 02:27 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com