Intro:
I am aware that - showing UserForms - it's best practice to
- handle
QueryClose
within the userform code (If CloseMode = vbFormControlMenu ...
) - doing no
Unload Me
therein, just a timidMe.Hide
instruction (after preventing [x]-itting and eventual self-destruction viaCancel = True
) - setting a related variable/[property] within the [class] code (e.g.
.IsCancelled=True
) - in order to be able to have the UF unloaded by the calling code.
Useful link
An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/ as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).
Further selection (►edit as of 5/1 2019)
- Disadvantages in putting code into userforms instead of modules
- Passing variable from form to module
- Apply logic for userform dialog (Rubberduck)
- The perfect userform (Vitosh academy)
1) Working examples for modal UserForms
As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:
Case 1a) .. with a local variable for the UF instance, as often seen:
Public Sub ShowFormA
Dim ufA As UserForm1
Set ufA = New UserForm1
' show userform
ufA.Show ' equivalent to: ufA.Show vbModal
' handle data after user okay
If Not ufA.IsCancelled Then
' do something ...
End If
' >> object reference destroyed expressly (as seen in some examples)
unload ufA
End Sub
Case 1b) .. without a local variable, but using a With New
codeblock:
' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
' as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
With New UserForm1
.Show ' equivalent to: ufA.Show vbModal
' handle data after user okay
If Not .IsCancelled Then
' do something ...
End If
End With
2) Problem
Problems arise using a MODELESS UserForm instance.
Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:
With New UserForm1
.Show vbModeless ' << show modeless uf
End With
If I try, however to
- a) get information about a possible user cancelling as well as
- b) to
Unload
a form if baptized using a local variable (e.g. "ufA") after theShow
instruction,
all code lines will be executed at once for precisely the reason that the form is MODELESS:
- code shows the form, the next moment ..
- code finds no user cancelling, as there was no time for any user action, the next moment ..
- [code unloads the form if using a local variable for the userform]
3) Question
How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?
If Not
**Ufa**.IsCancelled
in 1a) - one should keep away from copying an apparently similar code some lines below (cf. 1b) :-). Nevertheless I hope having contributed a helpful question at least for learning programmers. – T.M.