Sometimes it is useful to highlight a selected item in a combo box or a text box for easy text replacing.
First of all, as many developers know, when you want to get into a form changing the active control and highlighting it, you simply can write:
Private Sub High(C As Control)
C.SetFocus ' It's important when you want to go to a control with tabindex <> 0.
If C.Text = "" Then Exit Sub
C.SelStart = 0
C.SelLength = Len(C.Text)
End Sub
Private Sub UserForm_Activate()
Call High(Me.Ctrl)
End Sub
However, inside a userform edition, when you click in a text box control, the content does not get highlighted. On the other hand, if you get into the control using tabs, the current content it is highlighted by default.
The solution for click event is not use the Enter event, but the MouseDown event:
Private Sub Ctrl_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, _
ByVal Y As Single)
If Button = xlPrimaryButton And Shift = 0 Then
Call High(Me.Ctrl)
End If
End Sub
It works for Combo Boxes and Text Boxes.
Most believe that Enter event would work on that situation, but it doesn't, because the Enter event change the active control for the destination but not completely. It runs before MouseDown event, therefore before the mouse click action and its consequences.
Besides, I have not found any reference that the above trick works well also for combo boxes. It is cool because a user can type just the initials for fast selection, without manually erase the current item.
Version: Excel 2003 to Excel 2010
Bookmarks