我希望在文本框控件中检查数据验证,如果无效,则返回该文本框中的光标,不要让用户逃脱。 但.setfocus方法无法正常工作,当用户在初始文本框中输入无效数据时,光标将在单击另一个文本框或按Tab键后跳转到另一个文本框。
我试过这段代码:
Private Sub txtFirst_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Not IsNumeric(txtFirst.Text) Then
lblStatusBar = "Error1"
txtFirst = ""
txtFirst.SetFocus
Exit Sub
End If
If IsError(Application.Match(CInt(txtFirst.Value), Range("Table[Colulm1]"), 0)) Then
lblStatusBar = "Error2"
txtFirst.value=""
txtFisrt.SetFocus
exit sub
End If
lblStatusBar=""
End Sub
任何人都可以纠正吗?
答案 0 :(得分:2)
您需要通过设置取消=真来取消退出操作。
Private Sub txtFirst_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Not IsNumeric(txtFirst.Value) Then
lblStatusBar = "Error1"
txtFirst = ""
txtFirst.SetFocus
Cancel = True
'exit sub --> You dont need this here, the sub will exit anyway,
' unless there's more code after "End If"
End If
End Sub
答案 1 :(得分:0)
试试这个。这使用OERN (On Error Resume Next)
来检查是否导致错误。
Private Sub txtFirst_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim Ret
Dim rng As Range
With txtFirst
If Not IsNumeric(.Text) Then
lblStatusBar = "Error1"
.Value = ""
Cancel = True
Exit Sub
End If
On Error Resume Next
'~~> Change Sheet1 to relevant sheet
Set rng = ThisWorkbook.Sheets("Sheet1").Range("Table[#Colulm1]")
Ret = Application.Match(CInt(.Value), rng, 0)
If Err.Number <> 0 Then
Err.Clear
lblStatusBar = "Error2"
.Value = ""
Cancel = True
End If
On Error GoTo 0
End With
End Sub