Designtime versus runtime User Form manipulations

It's important to understand the distinction between manipulating UserForms or controls at design time and manipulating these objects at runtime. Runtime manipulations are apparent when the UserForm is shown, but the changes made are not permanent. For example, you might write code that changes the Caption property of the UserForm before the form is displayed. The new caption appears when the UserForm is shown, but when you return to the VBE, the UserForm displays its original caption. Part IV of this book contains many examples of code that perform runtime manipulation of UserForms and controls.

Design-time manipulations, on the other hand, are permanent—just as if you made the changes manually by using the tools in the VBE. Normally, you perform design-time manipulations as a way to automate some of the tedious chores in designing a UserForm. To make design-time manipulations, you access the Designer object for the UserForm.

To demonstrate the difference between design-time and runtime manipulations, I developed two simple procedures that add a CommandButton to a UserForm. One procedure adds the button at runtime; the other adds it at design time.

The following RunTimeButton procedure is very straightforward. When used in a general (non-UserForm) module, it simply adds a CommandButton, changes a few of its properties, and then displays the UserForm. The CommandButton appears on the form when the form is shown, but when you view the form in the VBE, the CommandButton is not there.

Sub RunTimeButton() ' Adds a button at runtime Dim Butn As CommandButton

Set Butn = UserForm1.Controls.Add("Forms.CommandButton.1")

With Butn

.Caption = "Added at runtime" .Width = 100 .Top = 10 End With UserForml.Show End Sub

Following is the DesignTimeButton procedure. What's different here is that this procedure uses the Designer object, which is contained in the VBComponent object. Specifically, it uses the Add method to add the CommandButton. Because the Designer object was addressed, the CommandButton is added to the UserForm just as if you did it manually in the VBE.

Sub DesignTimeButton() ' Adds a button at design time Dim Butn As CommandButton Set Butn = ThisWorkbook.VBProject. _ VBComponents("UserForml") _

.Designer.Controls.Add("Forms.CommandButton.l") With Butn

.Caption = "Added at design time" .Width = l20 .Top = 40 End With End Sub

0 0

Post a comment