Link to home
Start Free TrialLog in
Avatar of sajicmajic
sajicmajic

asked on

Initialising Global Variable

hi everybody,

I have a little problem with the vb. I have defined two sort of global variables. One global variable is defined in main module while one is defined in a form.

I like to know, how to initialise these variable. or in other word how to destroy these variable from the memory.

I have tried to set the form to nothing. but the variable still remains.

Please help me urgently

Sajid
Avatar of deighton
deighton
Flag of United Kingdom of Great Britain and Northern Ireland image

You can't remove them from memory, the variable defined in the module will always exist, and in VB5 onwards (I think)  the one in the form will always exist as well. You will be able to use the form variable irregardless of whether the form is loaded.

Why do you need to do this?
ASKER CERTIFIED SOLUTION
Avatar of PaulHews
PaulHews
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
in my vb version

Form 1

Option Explicit

Private Sub Command1_Click()
Form2.Show
End Sub

Private Sub Command2_Click()
MsgBox Form2.x
Unload Form2
End Sub

Private Sub Command3_Click()
MsgBox Form2.x
End Sub


Form2

Option Explicit

Public x As Long

Private Sub Form_Load()

x = 5

End Sub



  - sequence of msgboxes = 1,2,3  I get command 2 shows '5' as expected - command 3, still shows 5 even though the form is unloaded

Don't forget Deighton that you reference to Form2.x will reload the form even when it is unloaded. So it will always be thus.
Tim,

In that case I changed the form2 code to

Private Sub Form_Load()

x = x + 5
MsgBox "Hello!"


End Sub

 - in actual fact clicking on command 3 then simply displays the vaue '5'  - the load event is not fired by referencing the public variable in the form.  This is VB5 I'm using at the moment.  Does VB6 differ?

Yes, and if this wasn't here:

Private Sub Form_Load()

x = 5

End Sub

Then x would be empty (assuming variant) when 3 is clicked.
Deighton, try setting the form = nothing after you unload it.
..but I dont get the messagebox

in full, the form2 code is

Option Explicit

Public x As Long

Private Sub Form_Load()

x = 5
MsgBox "Hello!"


End Sub
No deighton, you are right.  The variable x is made empty, but the Form_Load doesn't run for command3.  This happens in VB 6 as well.

Avatar of corvanderlinden
corvanderlinden

Referencing a global variable in a form or a (selfdefined) property, implicit loads the form's data and code but not the form itself, so no Load event.

PaulHews is right : To get rid of data and code segment unload form and then set form to nothing.

Remember using Form2 you are using the (hidden) global Form2 instance

I prefer using :

dim x as Form2

set x = new Form2

'do the job and let x go out of scope, which is an implicit set x = nothing