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?
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.
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.
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.
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.
Any of these will reset global variables:
That's not necessarily an exhaustive list though...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With