Recondaddy
05-11-2010, 07:21 AM
Hello All,
I'm using VBA with Excel 2007, and I've run across a variable scope and lifetime issue that makes no sense to me. I was hoping that someone might be able to shed some light.
For testing purposes, I have a blank worksheet with a single command button on it (TestButton).
In the worksheet code I have the following Sub:
Private Sub Workbook_Open()
MyVariable = 1
ThisWorkbook.ActiveSheet.Range("A1") = MyVariable
End Sub
So, as you can see, when the workbook loads, MyVariable is set to '1' and the value is displayed at cell A1. MyVariable is declared as a Public variable at the top of Module1 so that it can be used globally.
Here's what makes no sense. I use the TestButton to display the value of MyVariable in cell A2, whenever I click the button. But, if I place the event handler of the button in a separate module (Module2), MyVariable always retains the value it was given when the workbook opened.
However, if I place the event handler in the same module where the declaration of MyVariable resides (Module1), the value of MyVariable is always reset whenever I click the button:
Public MyVariable As Integer
Sub TestButton_Click()
ThisWorkbook.ActiveSheet.Range("A2") = MyVariable
End Sub
Can anyone explain to me why MyVariable doesn't retain its value in this case?
Thanks for any help you can provide.
I'm using VBA with Excel 2007, and I've run across a variable scope and lifetime issue that makes no sense to me. I was hoping that someone might be able to shed some light.
For testing purposes, I have a blank worksheet with a single command button on it (TestButton).
In the worksheet code I have the following Sub:
Private Sub Workbook_Open()
MyVariable = 1
ThisWorkbook.ActiveSheet.Range("A1") = MyVariable
End Sub
So, as you can see, when the workbook loads, MyVariable is set to '1' and the value is displayed at cell A1. MyVariable is declared as a Public variable at the top of Module1 so that it can be used globally.
Here's what makes no sense. I use the TestButton to display the value of MyVariable in cell A2, whenever I click the button. But, if I place the event handler of the button in a separate module (Module2), MyVariable always retains the value it was given when the workbook opened.
However, if I place the event handler in the same module where the declaration of MyVariable resides (Module1), the value of MyVariable is always reset whenever I click the button:
Public MyVariable As Integer
Sub TestButton_Click()
ThisWorkbook.ActiveSheet.Range("A2") = MyVariable
End Sub
Can anyone explain to me why MyVariable doesn't retain its value in this case?
Thanks for any help you can provide.