Lifetime and Scope of variables

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,926
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
I am a bit confused with regard to the Lifetime and Scope of variables.


Given this code:

Code:
Option Explicit


    Dim a As Integer


Sub FromSheet1()


    Sheet3.Select
    
    a = 1
    
End Sub


Sub FromSheet2()



    Sheet3.Select
    
    a = 2
    
End Sub



Sub GoBack()


    If a = 1 Then Sheet1.Select ' PUT BREAK POINT HERE
    
    If a = 2 Then Sheet2.Select


End Sub

After running Sub FromSheet1 through to End Sub, if I go to the immediate window and type:

Code:
? a


I get a blank, which suggests to me the variable a has been cleared out because Sub FromSheet1 has finished running.


But if I subsequently run Sub FromSheet3 and put a break point as indicated, then go to the immediate window, it somehow "remembers" that a = 1.



Is this because the variable a has been declared at the module level?


Thanks
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
I don't what version of Excel you are running, but in Excel 2013, I have to use:
Debug.print a
to display a result in the Immediate window.

When I do exactly as you stated above, my result for "a" after I run the "FromSheet2" sub is 2

Jeff
 
Upvote 0
Your variable is scoped to the module, hence not read in the Immediate window unless you are currently running code in that module. If you made it public, you would see ?a produce the correct result even when no code is running.
 
Upvote 0
Code:
Option Explicit

Dim a As Integer

Sub init()
  a = 1
End Sub

Run init, then from the Immediate window,

Code:
? module1.a

... changing module1 as appropriate.
 
Upvote 0

Forum statistics

Threads
1,224,822
Messages
6,181,165
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top