Results 1 to 10 of 10

Thread: Which control will gain the focus on a form

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #10
    VBAX Regular
    Joined
    Sep 2013
    Posts
    18
    Location
    Sticking to VBA, I found an even better method, totally foolproof and with minimal coding:
    I noticed that the tooltips work without raising the exit event for a control. So obviously the userform kbnows where the mouse is.

    So in the situation where the action when leaving a control depends on which control the mouse is over then the following works. This could be because you don't want to raise a 'missing value' message if the user presses cancel, or as in my case, don't want to ask the user if the form should be updated with the changed values, if he presses 'Save to Sheet'.

    A private boolean flag bOn is checked by the control_Exit sub (in my case the control is a Frame where the textboxes reside)
    If the flag is true no checking is done
    The flag is set true by the sub that records if the mouse is over the 'Save to Sheet' button (or cancel button depending how you want to use it)
    The flag is set to off by the sub that records if the mouse is over the Userform.
    This is necessary as the user could just move the mouse over the button without clicking.

    Here is the simple code:
    Option Explicit
    Dim bOn  As Boolean
    
    Private Sub CommandButton1_Click()
        ' do save or whatever
        '....
        bOn = False
    End Sub
    
    Private Sub CommandButton1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
        'set a flag that user is over the Save button, so avoid the Exit check
        bOn = True
    End Sub
    
    Private Sub Frame1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        ' if user clicks outside frame then check if fields in frame _
          have been filled out properly. If the bOn flag is true, then _
          the user is over a button, (such as cancel button) that means _
          the check is not required
        If bOn = False Then
            If TextBox1.Value = vbNullString Then MsgBox "Empty" Else MsgBox "Full"
        End If
    End Sub
    
    Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
        ' set the flag back to false once user moves away from button
        bOn = False
    End Sub
    Last edited by Aussiebear; 06-23-2025 at 02:51 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •