Is it possible to declare a public variable in vba and assign a default value?

后端 未结 8 702
旧时难觅i
旧时难觅i 2020-12-09 01:33

I want to do this but it won\'t compile:

Public MyVariable as Integer = 123

What\'s the best way of achieving this?

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 01:45

    Little-Known Fact:
    A named range can refer to a value instead of specific cells.

    This could be leveraged to act like a "global variable", plus you can refer to the value from VBA and in a worksheet cell, and the assigned value will even persist after closing & re-opening the workbook!


    • To "declare" the name myVariable and assign it a value of 123:

      ThisWorkbook.Names.Add "myVariable", 123
      
    • To retrieve the value (for example to display the value in a MsgBox):

        MsgBox [myVariable]
      
    • Alternatively, you could refer to the name with a string: (identical result as square brackets)

      MsgBox Evaluate("myVariable")
      
    • To use the value on a worksheet just use it's name in your formula as-is:

      =myVariable
      
    • In fact, you could even store function expressions: (sort of like in JavaScript)
      (Admittedly, I can't actually think of a situation where this would be beneficial - but I don't use them in JS either.)

      ThisWorkbook.Names.Add "myDay", "=if(isodd(day(today())),""on day"",""off day"")"
      

    Square brackets are just a shortcut for the Evaluate method. I've heard that using them is considered messy or "hacky", but I've had no issues and their use in Excel is supported by Microsoft.

    There is probably also a way use the Range function to refer to these names, but I don't see any advantage so I didn't look very deeply into it.


    More info:

    • Microsoft Office Dev Center: Names.Add method (Excel)
    • Microsoft Office Dev Center: Application.Evaluate method (Excel)

提交回复
热议问题