MOCKSTACKS
EN
Questions And Answers

More Tutorials









VBA User Forms

Best Practices


A UserForm is a class module with a designer and a default instance. The designer can be accessed by pressing Shift + F7 while viewing the code-behind, and the code-behind can be accessed by pressing F7 while viewing the designer.

Work with a new instance every time.


Being a class module, a form is therefore a blueprint for an object. Because a form can hold state and data, it's a better practice to work with a new instance of the class, rather than with the default/global one:

With New UserForm1
 .Show vbModal
 If Not .IsCancelled Then
 '...
 End If
End With

Instead of:

UserForm1.Show vbModal
If Not UserForm1.IsCancelled Then
 '...
End If

Working with the default instance can lead to subtle bugs when the form is closed with the red "X" button and/or when Unload Me is used in the code-behind.

Implement the logic elsewhere.


A form should be concerned with nothing but presentation: a button Click handler that connects to a database and runs a parameterized query based on user input, is doing too many things.

Instead, implement the applicative logic in the code that's responsible for displaying the form, or even better, in dedicated modules and procedures.

Write the code in such a way that the UserForm is only ever responsible for knowing how to display and collect data: where the data comes from, or what happens with the data afterwards, is none of its concern.

Conclusion

In this page (written and validated by ) you learned about VBA User Forms . What's Next? If you are interested in completing VBA tutorial, your next topic will be learning about: VBA CreateObject vs GetObject.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.