Coloring the Active Control

Another method for helping a user fill out a form is to color the active field. The following example changes the color of a text box or combobox when it is active, as shown in Figure 21.16.

Figure 21.16

Help users keep track of which field they're filling in by coloring the field when it is active.

Figure 21.16

Help users keep track of which field they're filling in by coloring the field when it is active.

Place the following in a class module called clsCtlColor: Public Event GetFocus()

Public Event LostFocus(ByVal strCtrl As String) Private strPreCtr As String

Public Sub CheckActiveCtrl(objForm As MSForms.UserForm)

With objForm

If TypeName(.ActiveControl) = "ComboBox" Or _ TypeName(.ActiveControl) = "TextBox" Then strPreCtr = .ActiveControl.Name On Error GoTo Terminate Do

DoEvents

If .ActiveControl.Name <> strPreCtr Then

If TypeName(.ActiveControl) = "ComboBox" Or _ TypeName(.ActiveControl) = "TextBox" Then RaiseEvent LostFocus(strPreCtr) strPreCtr = .ActiveControl.Name RaiseEvent GetFocus End If End If

Loop End If End With

Terminate: Exit Sub

End Sub

Place the following behind the userform: Private WithEvents objForm As clsCtlColor

Private Sub UserForm_Initialize() Set objForm = New clsCtlColor End Sub

This sub changes the BackColor of the active control when the form is activated.

Private Sub UserForm_Activate() If TypeName(ActiveControl) = "ComboBox" Or _ TypeName(ActiveControl) = "TextBox" Then ActiveControl.BackColor = &HC0E0FF End If objForm.CheckActiveCtrl Me End Sub

This sub changes the BackColor of the active control when it gets the focus.

Private Sub objForm_GetFocus() ActiveControl.BackColor = &HC0E0FF End Sub

This sub changes the BackColor back to white when the control loses the focus.

Private Sub objForm_LostFocus(ByVal strCtrl As String) Me.Controls(strCtrl).BackColor = &HFFFFFF End Sub

This sub clears the objForm when the form is closed.

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) Set objForm = Nothing End Sub

0 0

Responses

  • Elisa
    What is .activecontrol in vb?
    7 years ago

Post a comment