Multiple Choice 2
Up
Here is some code that you could use for your cmdEndTest button:
Private Sub cmdEndtest_Click()
For n = 1 To numq   ' loop through the questions
    score = score - (response(n) = correct(n)) ' the TRUE condition is taken to equal -1
Next
MsgBox ("Your score is " & score & " out of " & numq & " or " & Format(score / numq, "0%"))
End
End Sub

The procedure uses the equality operator to test whether the student's response is equal to the correct answer. When forced to treat a TRUE condition as a number, VB will take it to equal minus 1 (FALSE is taken to equal zero). Thus for each correct response detected, minus 1 is subtracted from score, which is equivalent to adding one to score.

Note that the = sign is ambiguous in Visual Basic - it's usually used as the Assignment Operator to set a variable to the value to the expression the the right of the operator, but sometimes it is used to test the equality of two expressions. Only context and common sense tells you when the = sign is used in one way and when it is used in the other. The score line of the above code contains an example of both uses of the = operator.

In the messagebox line, the FORMAT function is used to specify that the result is to be displayed as a percentage, with no decimal places.

Up Next