'--- Code for an UserForm module---
Option Explicit
Private arrTxb() As New Class1
Private arrCmb() As New Class1
Private Sub UserForm_Activate()
GetFocus
End Sub
Private Sub UserForm_Initialize()
Dim obj As MSForms.Control, i As Long, j As Long
For Each obj In Me.Controls
If TypeName(obj) = "TextBox" Then
ReDim Preserve arrTxb(i)
Set arrTxb(i) = New Class1
arrTxb(i).SetTextBox obj
i = i + 1
End If
If TypeName(obj) = "ComboBox" Then
ReDim Preserve arrCmb(j)
Set arrCmb(j) = New Class1
arrCmb(j).SetComboBox obj
j = j + 1
End If
Next
End Sub
'--- Code for a Class Module Named Class1 ---
Option Explicit
Public WithEvents cls_txb As MSForms.TextBox
Public WithEvents cls_cmb As MSForms.ComboBox
Sub SetTextBox(ByVal txb As MSForms.TextBox)
Set cls_txb = txb
End Sub
Sub SetComboBox(ByVal cmb As MSForms.ComboBox)
Set cls_cmb = cmb
End Sub
Private Sub cls_txb_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
LostFocus objPre
End Sub
Private Sub cls_cmb_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
LostFocus objPre
End Sub
Private Sub cls_txb_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
CallLoastFocus KeyCode, cls_txb
End Sub
Private Sub cls_cmb_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
CallLoastFocus KeyCode, cls_cmb
End Sub
Private Sub CallLoastFocus(ByVal KeyCode As Long, ByVal MSFCtrl As MSForms.Control)
If KeyCode = 13 Or KeyCode = 9 Or KeyCode = 40 Or KeyCode = 38 Then
LostFocus MSFCtrl
End If
End Sub
'--- Code for a Standard Module ---
Option Explicit
Public objPre As MSForms.Control
Public Sub LostFocus(ByVal obj As MSForms.Control)
If TypeName(obj) = "TextBox" Or TypeName(obj) = "ComboBox" Then
obj.BackColor = &HFFFFFF
End If
Application.OnTime Now, "GetFocus"
End Sub
Public Sub GetFocus()
Dim objActive As MSForms.Control
'Change Userform Name to suit.
Set objActive = UserForm1.ActiveControl
If TypeName(objActive) = "TextBox" Or _
TypeName(objActive) = "ComboBox" Then
objActive.BackColor = &HC0E0FF
End If
Set objPre = objActive
Set objActive = Nothing
End Sub