简体   繁体   中英

Excel VBA Variable value Scope - assign value to a variable for all subs

I am writing a module with several subs, and I need some variables to have the same value in all the modules. I know about declaring variables as

Public varname as vartype

but how can I assign a global value to such a variable?

Thanks

For a worksheet object (any object for that matter) you need to do the following:

In a standard code module:

Public varName As Excel.Worksheet

In the Workbook_Open() event:

Private Sub Workbook_Open()
    Set varName = Sheets("mySheet")
End Sub

Then you can refer to varName in any other module for that workbook and it will point to your worksheet object.


From your question/comments, it seems that you actually want some sort of object constant, which can't be done in VBA - see Declare a Workbook as a Global variable for more infromation.

If you're referring to a value data type such as String , Integer or Long then you can use a constant instead of a variable, however a constant's value cannot be changed once it has been declared (kind of the definition of 'constant') ie

Public Const someName As String = "Macro Man"
Public Const someNumber As Long = "1234567890"
Public Const someInt As Integer = "1453"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM