-
I have several questions related to an exercise where there are two text boxes where a user enters a number in each and clicks on a command button to sum all the numbers in between including the two entered then which places the result in a label box.
1) How do I code to perform the summation when the user presses the enter key in either text box?
2) How do I display the result in red for negative numbers and black for zero or positive numbers?
3) How do I restrict the application to handle entries from -32768 thru 32767 referring to these constants using constant identifiers (e.g. MIN_VALUE and MAX_VALUE) and also restirct the user to enter no more than 6 characters?
4) How do I make the summation work if the first value entered is more than the second (I.e. sum from the second value to the first)?
Thanks for any help.
-
1) if val(text1)>0 and val(text2)>0 then
label3=val(text1+text2)
2)if RESULT<0 then
label1.forecolor=vbred else
label1.forecolor=vbblack
3) dim min and max values as integers; set length property to 6 digits.
4)addition shouldn't matter which is greater.
Also, limit to number entries :
'Make sure it's a digit
tkeyascii = 0
If KeyAscii >= Asc(0) And KeyAscii <= Asc(9) Then tkeyascii = KeyAscii
If KeyAscii = 8 Then tkeyascii = 8
KeyAscii = tkeyascii
-
Q1/Q2:
Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = vbKeyReturn Then
Label1.Caption = Val(Text1) + Val(Text2)
If InStr(Label1.Caption, "-") Then
Label1.ForeColor = vbRed
Else
Label1.ForeColor = vbBlack
End If
End If
End Sub
Private Sub Text2_KeyPress(KeyAscii As Integer)
If KeyAscii = vbKeyReturn Then
Label1.Caption = Val(Text1) + Val(Text2)
If InStr(Label1.Caption, "-") Then
Label1.ForeColor = vbRed
Else
Label1.ForeColor = vbBlack
End If
End If
End Sub
-
Private Sub txtFrom_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case Is < 32
Case -32768 To 32767
Case Else
KeyAscii = 0
End Select
End Sub
Above is code I already have in KeyPress. How can I allow the enter key to be pressed and if it is, perform the summation of txtFrom and txtTo?
-
Isn't like this
If you look closer at his question, doesn't he need to know how to sum the numbers between and including the values in the textboxes. I think some of his code would have to be something like this.
Code:
Private Sub Command1_Click()
Dim i As Integer
Dim iFrom As Integer
Dim iTo As Integer
Dim tmp As Integer
Dim MyStep As Integer
iFrom = Val(txtFrom.Text)
iTo = Val(txtTo.Text)
If iFrom > iTo Then
MyStep = -1
Else
MyStep = 1
End If
For i = iFrom To iTo Step MyStep
tmp = tmp + i
Next i
Label1.Caption = tmp
End Sub
I know I am not addressing everything, and he doesn't want it in a command button. I was just trying to explain what I think he might need.