Thursday, May 28, 2020

VBA Excel Modeless Forms with BackColor using Rnd Function

We can use the UserForms collection to iterate through all loaded user forms in an application. It identifies an intrinsic global variable named UserForms. We can pass UserForms(index) to a function whose argument is specified as a UserForm class.

User forms can also respond to events initiated by a user or triggered by the system. For example, We can write code in the Initialize event procedure of the UserForm to initialize module-level variables before the UserForm is displayed.

UserForm is an Object data type. We can declare variables as type UserForm before setting them to an instance of a type of UserForm declared at design time. Similarly, We can pass an argument to a procedure as type UserForm. We can create multiple instances of user forms in code by using the New keyword in Dim, Set, and Static statements.

Option Explicit

Private Sub CommandButton1_Click()
    UserForm1.BackColor = vbBlue * Rnd
End Sub

Private Sub CommandButton2_Click()
    UserForm2.Show
    UserForm3.Show
    UserForm4.Show
End Sub

Private Sub CommandButton3_Click()
    Dim f As MSForms.UserForm
'''    Dim f As Object
    For Each f In UserForms
        If Not f Is Me Then
            f.BackColor = vbBlue * Rnd
        End If
    Next
End Sub

No comments:

Post a Comment

Hot Topics