vbams-word

Exit Event not triggering correctly on TextBoxes


I have a question for a form I 'm creating at the moment. It's basically a simple form to enter Network data. I have an algorithm to check for valid IPs and want the Textboxes to turn red in case wrong stuff is entered. That works well for most of the textboxes, but for some it shows a weird behavior.

Image of User Form:

enter image description here

I'm using the Exit Functions of the textboxes to do the check, so the boxes don't turn red immediately while you still enter things. Here is the code for that:

Private Sub LANGW_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If IsValidIP(AddHost.LANGW) = False Then AddHost.LANGW.BackColor = RGB(255, 0, 0) Else AddHost.LANGW.BackColor = RGB(255, 255, 255)
End Sub

Now to the issue. This code works fine for all textboxes except the last ones on each framed area. In this Case the Lan Gateway and Query/Retrieve. Those aren't triggered when I leave the textBox but rather when I come back to the same framed area after having exited the TextBox once. Can anyone come up with an explanation for this? I already looked through the Microsoft description of the exit event, but couldn't find anything.


Solution

  • So I figured it out. Here is the answer for all that stumble across the same issue.

    It seems that the exit events are only processed inside the same frame. If I exit this TextBox with my mouse to another TextBox inside the same frame it works. Only if I exit to another frame it doesn't. The exit event is however stored in that Frame and will be executed once the frame gets focus again. That's why I get the weird behavior of the script executing when jumping back into the frame.

    To work around this I now simply put the same checks to the frame exit event as well and that works just fine. Because those will be executed when you exit to another frame. (Yes that will have the consequence that the code will be executed a second time if the Frame gets focus again, but in this specific case that doesn't really hurt. In case you want to execute something more meaningful for such an event you should limit the check to just the frame exit event)

    Example:

    Private Sub LAN_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    
    If IsValidIP(AddHost.LANIP) = False Then AddHost.LANIP.BackColor = RGB(255, 0, 0) Else AddHost.LANIP.BackColor = RGB(255, 255, 255)
    If IsValidIP(AddHost.LANSubnet) = False Then AddHost.LANSubnet.BackColor = RGB(255, 0, 0) Else AddHost.LANSubnet.BackColor = RGB(255, 255, 255)
    If IsValidIP(AddHost.LANGW) = False Then AddHost.LANGW.BackColor = RGB(255, 0, 0) Else AddHost.LANGW.BackColor = RGB(255, 255, 255)
    
    End Sub