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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS