Public Static variable in excel vba

前端 未结 3 841
小鲜肉
小鲜肉 2021-02-05 19:33

Is it possible to have a static variable declared in one procedure, and use this variable in several different procedures using Excel VBA?

i.e.

Public m         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 19:50

    Although this question was answered over four years ago by @Gary's Student, there's a subtle nuance worth mentioning, since the solution can depend on the data type of myvar.

    First of all, as you've noted in the question, Public Static myvar as Integer doesn't work, because Static is only allowed inside a sub or function.

    As noted in the comments to the OP by @Patrick Lepelletier, you can easily get around this by declaring a Constant instead (assuming you don't need to change it dynamically): Public Const myvar as Integer = 999. (Or possibly Private Const myvar...)

    Another option is to declare myvar as a function instead of a variable or constant, effectively turning it into a pseudo-constant:

    Private Function myvar() as Integer
         Static intMyvar as Integer 
         intMyvar = 999
         myvar = intMyvar
    End function
    

    In this simple example where myvar is an integer, the pseudo-constant approach is obviously unnecessary and adds the overhead of a function call. Simply declaring a Constant does the job. However, using a constant only works if the value is static and not an object. It will not work if myvar is an object, for example a Range. In that case, using pseudo-constants might be useful:

    Private Function myvar() as Range
        Set myvar = Range("A1")
    End Function
    

    Another advantage is that you can use code inside the function to check for certain conditions and assign different values to myvar accordingly.

    The pseudo-constant approach can also be combined with naming worksheet ranges: If cell A1 is a named range, say MyRange, then you could write:

    Dim strMyString as String
    strMyString = "MyRange"
    Private Function myvar() as Range
        Set myvar = Range(strMyString)
    End Function
    

    Now it is possible to move around the content of cell A1 without breaking the code, since the named range follows along if you cut and paste the cell. I find this approach useful in the design stage, when things tend to move around a lot in a worksheet.

    Pseudo-constants also help avoiding some problems usually associated with global (or module-level) variables that might be an issue in larger projects.

提交回复
热议问题