我在用户窗体上有一个文本框。它是表单上唯一的文本框。除了这个文本框之外,还有三个标签和两个按钮。基本上,除了单击其中一个按钮的那一刻之外,我希望在所有情况下都将焦点保留在此文本框上,但随后我希望焦点立即回到文本框。两个按钮都将“TakeFocusOnClick”和“TabStop”设置为 False。我在将焦点设置到文本框时遇到问题,这就是我更改这两个设置的原因。
一旦我更改了这些设置,文本框中的 Enter 键就不再起作用。我为文本框的 _AfterUpdate 和 _KeyPress 编写了事件,但它们不会触发。正如您在代码中看到的那样,我已经注释掉了将焦点设置到此文本框的行。由于它现在是唯一可以聚焦的对象,因此不需要这些线(理论上)。当我允许其他对象获得焦点时,这些线没有任何效果(尽管有这些 SetFocus 线,焦点仍切换到按钮)。
这是代码。这很简单,只是 Enter 键没有触发事件。谁能明白为什么?谢谢。
Private Sub btnDone_Click()
Application.Calculation = xlCalculationAutomatic
formMath.Hide
'Clear statistics
Range("attempts").Value = 0
Range("correct").Value = 0
Sheet5.Range("A2:W500").ClearContents
End Sub
Private Sub btnSubmit_Click()
recordAnswer
'formMath.txtAnswer.SetFocus
End Sub
Private Sub txtAnswer_AfterUpdate()
recordAnswer
'formMath.txtAnswer.SetFocus
End Sub
Private Sub txtAnswer_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii = 13 Then
recordAnswer
End If
End Sub
Private Sub UserForm_Initialize()
'Initialize manual calculation
Application.Calculation = xlCalculationManual
Application.Calculate
'Initialize statistics
Range("attempts").Value = 0
Range("correct").Value = 0
Sheet5.Range("A2:W500").ClearContents
'Initialize first problem
newProblem
End Sub
Sub recordAnswer()
'Update statistics
Dim attempts, correct As Integer
attempts = Range("attempts").Value
correct = Range("correct").Value
Range("results").Offset(attempts, 0).Value = attempts + 1
Range("results").Offset(attempts, 1).Value = lblTopNum.Caption
Range("results").Offset(attempts, 2).Value = lblBotNum.Caption
Range("results").Offset(attempts, 3).Value = lblBop.Caption
Range("results").Offset(attempts, 4).Value = Range("Answer").Value
Range("results").Offset(attempts, 5).Value = txtAnswer.Text
If (Range("Answer").Value = txtAnswer.Text) Then
Range("results").Offset(attempts, 6).Value = 1
Else
Range("results").Offset(attempts, 6).Value = 0
End If
'Update attempts and success
Range("attempts").Value = attempts + 1
Range("correct").Value = correct + 1
newProblem
End Sub
Sub newProblem()
Application.Calculate
formMath.lblTopNum.Caption = Range("TopNum").Value
formMath.lblBotNum.Caption = Range("BotNum").Value
formMath.lblBop.Caption = Range("ProbType").Value
formMath.txtAnswer.Value = ""
'formMath.txtAnswer.SetFocus
End Sub