BruceWayne
BruceWayne

Reputation: 23283

Declare and define a variable globally (within Module)?

I have a module ("Module1") which has a few macros. Some of those I run back to back (it splits up the code length and makes it easier to debug/troubleshoot). At the top of that module, I have:

Option explicit
Dim addressFileName as String

Sub noOne()
addressFileName = "C:\Batman.xslx"
End Sub

Sub noTwo()
msgbox("You want to use the file " & addressFileName)
End Sub

Works great if I run noOne() then noTwo() after it. However, if I have to debug in subTwo() and start the macro over, it doesn't recognize "addressFileName".

Is there a way I can define addressFileName to be used globally as well? Simply adding addressFileName = "C:\Batman.xslx after declaring it doesn't work ("Compile error: Invalid outside procedure").

Is this possible? Or is there perhaps some workaround? Or is there a good reason you can't do this (if so, I'd love to know!). Thanks for any ideas!

Upvotes: 1

Views: 70

Answers (1)

user4039065
user4039065

Reputation:

Is there a way I can define addressFileName to be used globally as well?

Use

public const addressFileName as string  = "C:\Batman.xslx"

Note that you will not be able to alter the string but it can be referenced from anywhere in your project. This needs to be at the top of a module sheet, not a worksheet code sheet. See Declaring Constants for more information.

Upvotes: 2

Related Questions