Oscar
Oscar

Reputation: 13

Excel Macro and command buttons

I've created an UserForm in Outlook VBA and I have the option buttons set up to provide different options upon selection and everything works fine if I only go through once however,

Upvotes: 1

Views: 89

Answers (1)

Mathieu Guindon
Mathieu Guindon

Reputation: 71227

If I go back through a second time the option button from the previous run through is still selected.

You're showing the form's default instance.

UserForm1.Show

What you're seeing means you have a transient, global-scope object that's keeping its state between calls.

If you want to "start clean" every time you show that form, you have two options - one would be to Unload the transient object when you're done with it:

UserForm1.Show
'do stuff
Unload UserForm1

Another (much cleaner IMO) would be to stop using that global-scope object, and create one that's locally scoped instead, with a much clearer lifespan:

With New UserForm1 ' object created here
    .Show
    'do stuff
End With ' object dies here

Or:

Dim frm As UserForm1
Set frm = New UserForm1 ' object created here
frm.Show
'do stuff
'frm object goes out of scope and is destroyed at the end of the procedure

Whether that breaks your other code, depends on how much of that other code is written against the form's default instance. You're using Me in the sample code you've provided, and that's a good sign: it means you've written the code against whatever the current instance is, as opposed to e.g. For Each c In UserForm1.Controls, which would be iterating the controls in the form's default instance - which may be in a different state than the controls in the current instance.

For more information about working with forms, see UserForm1.Show, an article I wrote last year that explains in details what's wrong with the default instance approach.

Upvotes: 1

Related Questions