| Start | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Best Practices A 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: Instead of: Working with the default instance can lead to subtle bugs when the form is closed with the red "X" button and/or when Implement the logic elsewhere.A form should be concerned with nothing but presentation: a button 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. Caller shouldn't be bothered with controls.Make a well-defined model for the form to work with, either in its own dedicated class module, or encapsulated within the form's code-behind itself - expose the model with This means code that looks like this: Instead of this: Handle the QueryClose event.Forms typically have a Close button, and prompts/dialogs have Ok and Cancel buttons; the user may close the form using the form's control box (the red "X" button), which destroys the form instance by default (another good reason to work with a new instance every time). The simplest way to handle the That way the "X" button will never destroy the instance, and the caller can safely access all the public members. Hide, don't close.The code that creates an object should be responsible for destroying it: it's not the form's responsibility to unload and terminate itself. Avoid using Name things.Use the properties toolwindow (F4) to carefully name each control on a form. The name of a control is used in the code-behind, so unless you're using a refactoring tool that can handle this, renaming a control will break the code - so it's much easier to do things right in the first place, than try to puzzle out exactly which of the 20 textboxes Traditionally, UserForm controls are named with Hungarian-style prefixes:
The problem is that when e.g. the UI gets redesigned and a
Whichever style is chosen, anything is better than leaving all controls their default names. Consistency in naming style is ideal, too. |
||||||||||||||||||
| Handling QueryClose The
For better readability, it's best to use these constants instead of using their value directly. A Cancellable UserFormGiven a form with a Cancel button The form's code-behind could look like this: The calling code could then display the form, and know whether it was cancelled: The |
Read Article
https://develop.horje.com/learn/1434/reference