
January 14th, 2013, 09:23 PM
|
|
|
Quote: | Originally Posted by dabadguy4273 Alright so, i'm new to Visual Basic and i'm trying to make just a simple program that tells you if the number entered in the text box is positive or negative when you click the button. I'm not sure if the code i put on the button is wrong or if nothing I did was right xD Here's the code for the button.
Sub checkposneg()
If text1 <= 0 Then Print "Positive"
If text1 >= 0 Then Print "Negative"
End Sub
and i'm pretty sure that almost none of it is right xD |
What you have to appreciate is that the contents of a TextBox are treated as a Variant. Since you are entering text, the variant will be treated as text, but what you are after is the numerical value. Create a new project and add a text box (default name Text1) and a CheckBox (default name Check1). Change the text property of Text1 to (blank), and Change the Caption property of Check1 to "Positive". Add the following code:
Code:
Function CheckPos(vNum As Variant) As Boolean
If Val(vNum) >= 0 Then
CheckPos = True
Else
CheckPos = False
End If
End Function
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
If CheckPos(Text1.Text) Then
Check1.Value = 1
Else
Check1.Value = 0
End If
End If
End Sub
I have renamed the subroutine "checkposneg" that you wrote to a function "CheckPos" so that it will return a value. When you enter a number in the text box and hit the Enter key, it will call the function and the function will check the value of the text and return either "True" or "False". That value is used to set the Check Box.
J.A. Coutts
|