VBA Global variables no longer declared after deleting worksheet

前端 未结 2 1126
南笙
南笙 2021-01-18 18:21

I have some public worksheet variables that are first initialized when the workbook is open. I have a button that does this essentially:

Dim Response As Var         


        
相关标签:
2条回答
  • 2021-01-18 18:54

    I just tested it using Comintern foo. It's interesting that the standard module foo losses it value but the public foo variable in a worksheet module does not loses it's value.

    0 讨论(0)
  • 2021-01-18 19:12

    The reason is actually really simple - a Worksheet is a class in VBA, and its code module gets compiled along with the rest of your project even if it's empty. When you delete a worksheet and let code execution stop, the next time you run some code the VBE has to recompile the project because you removed a code module. That causes your custom class extensions to lose their state.

    Note that this does not happen unless the code stops running and is recompiled. This works just fine:

    Sheet1.foo = 42        'foo is a public variable in Sheet1
    Sheet2.Delete
    Debug.Print Sheet1.foo 'Prints 42
    
    0 讨论(0)
提交回复
热议问题