这是我用 vb6 编写的代码...它在 text1.setfocus 中显示错误
Private Sub Text1_Lostfocus()
s1 = Text1.Text
flag = 0
If Text1.Text = "" Then
flag = 1
End If
For i = 1 To Len(s1)
l = Mid(s1, i, 1)
If IsNumeric(l) = True Then
flag = 1
Exit For
End If
Next i
If flag = 1 Then
MsgBox "Enter valid input"
Text1.ForeColor = vbRed
Text1.SetFocus
End If
End Sub
LostFocus中不要有这段代码,而是尝试在Validate事件中使用它,该事件会有一个cancel参数,如果设置Cancel = True(意味着光标不会退出控件)则无需执行setfocus
尝试以下操作:
Private Sub Text1_Validate(Cancel As Boolean)
If IsNumeric(Text1.Text) = False Then
MsgBox "Enter valid input"
Text1.ForeColor = vbRed
Cancel = True
End If
End Sub
如果您有一个空字符串,并且您尝试在循环中使用,您可能会得到无效的过程调用,请尝试此操作。如果文本为空,请一起跳过它,不要运行循环。
Private Sub Text1_Lostfocus()
s1 = Text1.Text
flag = 0
If Text1.Text = "" Then
flag = 1
else
For i = 1 To Len(s1)
l = Mid(s1, i, 1)
If IsNumeric(l) = True Then
flag = 1
Exit For
End If
Next i
endif
If flag = 1 Then
MsgBox "Enter valid input"
Text1.ForeColor = vbRed
Text1.SetFocus
End If
结束子
我们在一个大型项目中遇到了这个错误。在我们的例子中,原因在于将焦点设置在当时不可见的对象上。