Visual BASIC
ANSWERS
Visual Basic Tutorial Lesson on 24/07/2006
Exercise 2
Insert two more buttons (A and B) in the form in Exercise 1.
When A is clicked, the message in the label is 'Hi [Your name]. You clicked button A'.
When B is clicked, the message in the lable is 'Hi [Your name]. You clicked button B'.
Private Sub cmdUpdate_Click()
Dim UserName, MessageText As String
UserName = Text1.Text
MessageText = "Hi " & UserName & ", Welcome to VB."
Label1.Caption = MessageText
End Sub
Private Sub cmdClose_Click()
Unload cmdClose.Parent
End Sub
Private Sub cmdA_Click()
Dim UserName, MessageText As String
UserName = Text1.Text
MessageText = "Hi " & UserName & ", You clicked button A"
Label1.Caption = MessageText
End Sub
Private Sub cmdB_Click()
Dim UserName, MessageText As String
UserName = Text1.Text
MessageText = "Hi " & UserName & ", You clicked button B"
Label1.Caption = MessageText
End Sub
Exercise 3
Design a form with 2 Textbox, 2 CommandButton and 1 Label. Text1 and Text2 (Textbox) are data type currency. Command 1 is a command to sum the two numbers. The sum of the two numbers will be displayed in Label1.
Private Sub cmdSum_Click()
Dim Num1, Num2, Sum As Currency
Num1 = Text1.Text
Num2 = Text2.Text
Sum = Val(Num1) + Val(Num2)
Label1.Caption = Sum
End Sub
Private Sub cmdSum_Click()
Label1.Caption = Val(Text1.Text) + Val(Text2.Text)
End Sub
Private Sub cmdClose_Click()
Unload cmdClose.Parent
End Sub
Exercise 4
Add another Command to find the average of the numbers.
The average of the two numbers will be display in Label1
Private Sub cmdAverage_Click()
Dim Num1, Num2, Avg As Currency
Num1 = Text1.Text
Num2 = Text2.Text
Avg = (Val(Num1) + Val(Num2)) / 2
End Sub
Private Sub cmdAverage_Click()
Label1.Caption = (Val(Text1.Text) + Val(Text2.Text))/2
End Sub
Exercise 5
Write a VB program to accept a grade from user.
If mark is less than 40, the display "Your grade is FAIL. Don't Give Up!"
If mark is 40 and above, then display "Your grade is PASS. Congratulations"
Private Sub cmdResult_Click()
Dim Usermark As Integer
Dim Usercomment As String
Usermark = Text1.Text
Usergrade = ""
If Usermark >= 0 And Usermark <= 100 Then
  If Usermark < 40 Then
    Usergrade = "You grade is FAIL. Don't Give Up!"
  Else
      Usergrade = "You grade is PASS. Congratulations"
  End If
  lbResult.Caption = Usergrade
Else
  lbResult.Caption = "Invalid mark. Please enter again"
End If
End Sub
Private Sub cmdGrade_Click()
Dim Usermark As Integer
Dim Usergrade As String
Usermark = Text1.Text
Usergrade = ""
Select Case Usermark
Case Is >= 75
  Usergrade = "A (Distinction) - Excellent"
Case Is >= 65
  Usergrade = "B (Credit)- Good"
Case Is >= 40
  Usergrade = "C (Pass) - Congratulations"
Case Else
  Usergrade = "R (Referral) - Don't Give Up!"
End Select
lbResult.Caption = Usergrade
End Sub