Why is my .setfocus ignored?

2019-01-19 01:05发布

问题:

I have an Access form with a textbox that is meant to allow for repeatedly typing a number, hitting enter, and letting a script do stuff. For speed, the field should keep the focus after DoStuff() is done.

However, while I'm sure that DoStuff() is run, the focus always goes to the next field in the tab order. It's like Me.MyFld.SetFocus is being ignored.

How do I keep the focus on this field after DoStuff() is done?

Private Sub MyFld_KeyDown(KeyCode As Integer, Shift As Integer)  
     If KeyCode = vbKeyReturn Then  
         DoStuff  
         Me.MyFld.SetFocus  
     End If
End Sub

回答1:

If you look at the order of events for a keypress that would change focus, you can see that it always follows this pattern:

KeyDown → BeforeUpdate → AfterUpdate → Exit → LostFocus

You can re-set the focus anywhere in there and it will still keep following the pattern. So we need to tell it to stop following the pattern. Replace your Me.MyFld.SetFocus with DoCmd.CancelEvent and it should fix your problem. Basically, this just kicks you out of the above pattern, so the Exit and LostFocus events never fire...



回答2:

A workaround is moving the focus to another control and then back to the first control. Like this:

Private Sub MyFld_KeyDown(KeyCode As Integer, Shift As Integer)  
    If KeyCode = vbKeyReturn Then  
        DoStuff
        Me.anotherControl.SetFocus
        Me.MyFld.SetFocus  
    End If
End Sub


回答3:

  1. click on access options
  2. select Advanced
  3. select Don't move from Move after enter
  4. click ok

It will work 100%



回答4:

Try removing the whole line for variable_name.SetFocus and simply add: Cancel = True

Private Sub MyFld_KeyDown(KeyCode As Integer, Shift As Integer)  
     If KeyCode = vbKeyReturn Then  
         DoStuff  
         Cancel = True  
     End If
End Sub