vb中我想在一个文本框中输入某个数,然后按enter键之后,调用一个function

2025-02-23 14:57:29
推荐回答(2个)
回答1:

Private Sub Command1_Click()
  If Int(Val(Text1.Text)) <> Val(Text1.Text) Or Val(Text1.Text) <= 0 Or Val(Text1.Text) > 2147483647 Then
    MsgBox "数据错误!"
  ElseIf Val(Text1.Text) = 1 Then
    Label1.Caption = Text1.Text + "不是素数。"
  Else
    If IsPrimeNumber(Val(Text1.Text)) Then
      Label1.Caption = Text1.Text + "是素数。"
    Else
      Label1.Caption = Text1.Text + "不是素数。"
    End If
  End If
  Text1.SetFocus
End Sub

Private Function IsPrimeNumber(ByVal n As Long) As Boolean
  IsPrimeNumber = True
  For i = 2 To Sqr(n)
    If n Mod i = 0 Then
      IsPrimeNumber = False
      Exit For
    End If
  Next i
End Function

Private Sub Form_Load()
  Command1.Default = True
End Sub

回答2:

Private Sub Command1_Click()

Dim x As Long

x = Text1

yes = True

For i = 2 To Sqr(x)

If x Mod i = 0 Then

yes = False

Exit For

End If

Next i

If yes Then

Label1.Caption = x & " 是一个素数"

Else

Label1.Caption = x & " 不是一个素数"

End If

End Sub


Private Sub Text1_KeyPress(KeyAscii As Integer)

If KeyAscii = 13 Then

Call Command1_Click

End If

End Sub