Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the lifetime of a global variable in excel vba?

I've got a workbook that declares a global variable that is intended to hold a COM object.

Global obj As Object

I initalize it in the Workbook_Open event like so:

Set obj = CreateObject("ComObject.ComObject");

I can see it's created and at that time I can make some COM calls to it.

On my sheet I have a bunch of cells that look like:

=Module.CallToComObject(....)

Inside the Module I have a function

Function CallToComObject(...)
   If obj Is Nothing Then
        CallToComObject= 0
    Else
        Dim result As Double
        result = obj.GetCalculatedValue(...)
        CallToComObject= result
    End If
End Function

I can see these work for a bit, but after a few sheet refreshes the obj object is no longer initialized, ie it is set to Nothing.

Can someone explain what I should be looking for that can cause this?

like image 708
chollida Avatar asked Aug 12 '11 13:08

chollida


People also ask

What is the lifetime of a global variable?

These types of variables can be declared using the static keyword, global variables also have a static lifetime: they survive as long as the program runs. Example : static int count = 0; The count variable will stay in the memory until the execution of the program finishes.

What is the lifetime of a variable in VB?

The lifetime of a variable represents the period of time during which it can hold a value. Its value can change over its lifetime, but it always holds some value.

What is scope and lifetime of variable in Visual Basic?

Lifetime - Refers to how long or when the variable is valid (i.e. how long will it retain its value for). Scope - Refers to where the variable can be accessed. The Lifetime is how long the variable retains its value for. The scope refers to where the variable can be used.

How do global variables work in VBA?

VBA global variables are variables declared before any macro in the module starts. When the variables are declared using either “Public” or “Global,” it becomes a global variable. Sub Procedure Variables Cannot Use Anywhere. We usually declare the variable inside the subroutine in VBA.


2 Answers

Any of these will reset global variables:

  1. Using "End"
  2. An unhandled runtime error
  3. Editing code
  4. Closing the workbook containing the VB project

That's not necessarily an exhaustive list though...

like image 170
Tim Williams Avatar answered Sep 20 '22 19:09

Tim Williams


I would suggest a 5th point in addition to Tim's 4 above: Stepping through code (debugging) and stopping before the end is reached. Possibly this could replace point number 3, as editing code don't seem to cause global variable to lose their values.

like image 31
Excel Developers Avatar answered Sep 17 '22 19:09

Excel Developers