devxlogo

Form-Level Variables Won’t Clear

Form-Level Variables Won’t Clear

When you use multiple forms in a project, make sure you explicitly set a form to Nothing after you unload it. If you don’t, simply unloading the form won’t necessarily clear out variables from the form. Setting it to Nothing does reset form-level variables:

 Private Sub ShowNewForm()	Load Form2	Form2.Show vbModal	Unload Form2	Set Form2 = NothingEnd Sub

To see how the problem occurs, create a new standard executable project, with a form and a command button. Use this code:

 Option ExplicitPrivate Sub Command1_Click()	Load Form2	Form2.Show vbModal	Unload Form2	'Set Form2 = NothingEnd Sub

Add a second form with a label and a command button on it, and paste in this code:

 Option ExplicitPrivate msStuff As StringPrivate Sub Command1_Click()	HideEnd SubPrivate Sub Form_Load()	Label1.Caption = "value is " & msStuffEnd SubPrivate Sub Form_Unload(Cancel As Integer)	msStuff = "hey!"End Sub

Press the command button on Form 1 to show Form 2. The label control shows that the msStuff variable is empty. Hide Form 2 by pressing the button, then pressing the button on Form 1 again. This time, Form 2 will have a value in the msStuff variable, showing that it doesn’t clear out.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist