View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default Globals Go "Poof!": Workarounds?

First, if all you're doing is saving the workbook's name and its path, you could
use something like:

Thisworkbook.name
Thisworkbook.fullname
Thisworkbook.path

ThisWorkbook is the workbook that owns the code. And you can use that in any of
your routines.

But for other stuff, you may want to set up an initialization routine. Then you
can run that initialization routine whenever you need to:

Sub Workbook_Open()
Call InitialVars
End sub

========
In a general module:
Sub InitializeVars()
public VarsAreInitialized as boolean
public var1 as long
public var2 as string
public var3 as worksheet

varsareintialized = true
var1 = 323
var2 = "Ok"
set var3 = thisworkbook.worksheets("sheet1")
End sub

Then in any routine, you can check to see if your variables are ok:

Sub anyroutine()
if varsareintialized then
'perfect, do nothing!
else
call initializevars
end if
'stuff that does some real work
end sub

==========
If those variables change in other procedures, then this wouldn't be the way to
go--since it's just setting them back to their initial state.

PeteCresswell wrote:

In Workbook_Open() I'm capturing a couple of global variable values:
the workbook's name, and it's full path.

Naturally, when code is interrupted, the globals go "Poof!".

This is expected.... but I'm unable to make Workbook_Open a public
routine and call it as needed.

Seems like I need an alternative to global variables.

First thing that comes to mind is an invisible "System" or
"Application" worksheet that gets populated by Workbook_Open. Then I
write a couple of functions to grab the desired values from that
invisible sheet.

Does this sound like good practice?

Alternatives?


--

Dave Peterson