View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Chip Pearson Chip Pearson is offline
external usenet poster
 
Posts: 7,247
Default Scope of Public Variable

Your syntax
Public wbVLA08 = Application.ActiveWorkbook
is wrong because you cannot initialize a variable in its declaration. You
need to initialize in some initialization procedure, such as the Auto_Open
macro or the Workbook_Open event procedure. For example,

Public wbVLA08 As Workbook
Sub Auto_Open()
Set wbVBA08 = ActiveWorkbook
End Sub

Once initialized, it will retain its value until you change it or the
workbook is closed. You can then Activate that workbook at any time in code
with code like the following:

wbVLA08.Activate

Do I need to declare the variable in every module in which it is used?


No, declare it once in a standard code module (not the ThisWorkbook module
or a Sheet module or a class module), outside of and before any procedure.

Do I need to set in each module? Do I need to make it static?


No, declare it once. Public variables are "static" by definition.

If I understand it, I can't set in "This Workbook" which is what I'd like

to
do.


I'm not sure what the question is here. You can't declare it in the
ThisWorkbook module (well, you can, but shouldn't). In code, ThisWorkbook
always refers to the workbook containing the code, regardless of what
workbook happens to be active at some time. You may be able to simplify your
code to merely using ThisWorkbook to return to the workbook containing the
code. E.g.,

ThisWorkbook.Activate


--
Cordially,
Chip Pearson
Microsoft MVP - Excel
Pearson Software Consulting, LLC
www.cpearson.com




"Dkline" wrote in message
...
I want to create a Public variable upon the opening or reactivation of a
workbook.
Public wbVLA08 = Application.ActiveWorkbook

Then at various points in several modules I activate a different workbook,
do something there, and then want to make sure the original workbook is
activated. So I'd use:
wbVLA08.Activate

When a routine is called by another macro in which the Public variable has
been set, I get flagged on it saying object hasn't been set. "Run-time

error
91: Object variable or With block variable not set"

Do I need to declare the variable in every module in which it is used? Do

I
need to set in each module? Do I need to make it static?

If I understand it, I can't set in "This Workbook" which is what I'd like

to
do.

How can I do this?