VBA 如果复选框为真,则 SetFocus on Keydown 不起作用?

VBA SetFocus on Keydown not working if checkbox true?

我在 excel 中有以下表格。它是简单库存工作表的一部分,用于更新项目的状态。它按预期运行,但是当我尝试添加一个复选框以使所选状态持续存在时(允许我在处理一批项目时每次只输入序列而不是序列和状态)我注意到焦点在向前提交周期后,就好像我按下 tab 而不是我用 SetFocus.

设置它的位置

我假设这是与 KeyDown 的事件周期或嵌套 If/Else 逻辑相关的疏忽,但我并没有真正诊断出它。我最近才开始使用 VBA,我想了解很多怪癖。

Private Sub clear()
    Me.txtSerial = ""
    If cbPersist.Object.Value = False Then
        Me.cboxStatus = ""
        Me.cboxStatus.SetFocus
    Else
        Me.txtSerial.SetFocus
    End If
End Sub

Private Sub submit()
    Dim loc As Range
    Dim ws As Worksheet
    Set ws = Worksheets("Full Inventory")
    Set loc = ws.Columns("B").Find(what:=Me.txtSerial.Value, LookIn:=xlValues, lookat:=xlWhole)
    If Not loc Is Nothing Then
        ActiveWindow.ScrollRow = loc.Row
        ws.Cells(loc.Row, 10).Value = Me.cboxStatus.Value
    Else
        MsgBox "Serial not found."
    End If
    clear
End Sub

Private Sub txtSerial_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = vbKeyReturn Then
        submit
    ElseIf KeyCode = vbKeyEscape Then
        clear
    End If
End Sub

Private Sub UserForm_Initialize()
    cboxStatus.List = Array("Stock", "Shipped", "Research", "Sent Back", "Return")
End Sub

建议如下:

UserForm 模块的代码片段

Private Sub txtSerial_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
  If KeyCode = vbKeyReturn Then
    submit
    KeyCode = vbKeyPageDown     ' << modify Enter key value to prevent from tab hopping
  ElseIf KeyCode = vbKeyEscape Then
    clear
  End If
End Sub