storing a public variable for use in all modules

gordsky

Well-known Member
Joined
Jun 2, 2016
Messages
556
Office Version
  1. 2016
Platform
  1. Windows
I have a workbook with several modules in it some which run the same sections of code. I think I could probably create a function so that the code is only written once and then refer to that function on each sheet but what would really be useful would be if I could run the section of code once via workbook open and then store the result as MyValue which could then be used across any module. I have done lots of searches but cant find how to do it. I must confess I dont understand a lot of the results I have looked at so anyhelp with code or an explanation would be much appreciated
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
Just in any one of your modules at the top outside of a sub put
VBA Code:
Public SomeVariableName as Variant
Variant can be any data type
Then on open
VBA Code:
Private Sub Workbook_Open()
SomeVariableName = "Ha it worked"
End Sub
Please be aware I have had issues with this in the past where it doesn't hold the reference
This should be used in conjunction with the code being run on open, everywhere you run a new code you will have to set this again because VBA kills in when code ends
 
Upvote 0
Solution

Forum statistics

Threads
1,214,951
Messages
6,122,446
Members
449,083
Latest member
Ava19

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