Public Static variable in excel vba

前端 未结 3 844
小鲜肉
小鲜肉 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条回答
  •  借酒劲吻你
    2021-02-05 19:59

    The key is to use 2 variables. In the code below, myvar is public but not static. stvar is static but not public. Its scope is only within Main(). By assigning myvar=stvar and stvar=myvar, it effectively creates a variable that is both public and static. The value is preserved.

    Public myvar As String
    Sub Main() 'in module 1
    Static stvar As String
    myvar = stvar
    toInput
    stvar = myvar
    End Sub
    
    Sub toInput() 'in module2
    myvar = InputBox("enter something", "Input", myvar)
    End Sub
    

提交回复
热议问题