Logo 
Search:

MS Office Answers

Ask Question   UnAnswered
Home » Forum » MS Office       RSS Feeds
  Question Asked By: Raynard Fischer   on Nov 20 In MS Office Category.

  
Question Answered By: Jim Williamson   on Nov 20

Somehow I knew you'd ding me for not explicitly showing Option
Explicit. ;) So I rewrote new code  to create  a simple test, and
I'll list  all the code here.
Note: I went back to Walkenbach's VBA Power Programming book for
general code reference here to ensure I was doing it correctly.

I created a simple UserForm with two option buttons  titled Yes and
No, and added OK and Cancel buttons. The Yes makes variable  x = 1,
and the No makes x = 2.

Two Msgbox'es show the value at specific points in the code. The
Msgbox in the UserForm module shows  the right value, but in Module1
it shows a 0 as the variable doesn't carry over.

This code is from the Command Button on Sheet1 called Variable Test,
and resides in Microsoft Excel Objects -> Sheet1(Sheet1):
'------------------------------
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
'------------------------------

This code is in Forms -> UserForm1:
'------------------------------
Option Explicit
Public x As Integer

Private Sub OK_Button_Click()
If Yes_Button Then x = 1
If No_Button Then x = 2
MsgBox (x)
Call Var_Test
End Sub

Private Sub Cancel_Button_Click()
Unload UserForm1
End Sub
'------------------------------

And this code is in Module1:
'------------------------------
Option Explicit
Public x As Integer

Sub Var_Test()
MsgBox (x)
Unload UserForm1
End Sub
'------------------------------

It all works without an error, except that the variable x is correct
in the UserForm module  and then goes to 0 in the Module1 module.

Share: 

 

This Question has 7 more answer(s). View Complete Question Thread

 


Tagged: