RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Jun 7, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 = Nothing
End Sub

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

Option Explicit
Private Sub Command1_Click()
	Load Form2
	Form2.Show vbModal
	Unload Form2
	'Set Form2 = Nothing
End Sub

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

Option Explicit
Private msStuff As String
Private Sub Command1_Click()
End Sub
Private Sub Form_Load()
	Label1.Caption = "value is " & msStuff
End Sub
Private 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.

Joe Karbowski
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date