Search code examples
vbacalculationmsgbox

VBA doing random calculations and confirming right answer


Below code gives you a random calculation, you provide an answer and programme check if your answer was correct or not. Over all you get 5 examples to solve. At the end I would like to create a simple MsgBox stating in how many instances the user was right - Amount of correct answers.

This MsgBox is currently represented by "g". Unfortunately g = b + 0 in combination with g = b - 1 is not the correct way to go.

Can anybody help? Thank you!

Sub Main2()

Dim b, e, f, s1, s2 As Byte
Dim g As String

    g = 0
    For b = 1 To 5

    e = Round(Rnd() * 10)
    f = Round(Rnd() * 10)
        MsgBox ("Count: ") & Str(e) & (" *") & Str(f)
    s1 = InputBox("What's the result?")

    s2 = e * f
    If s1 = s2 Then
        MsgBox ("Correct")
        g = b + 0

    Else
        MsgBox ("Incorrect! Right answer is") & Str(s2)
        g = b - 1

        End If

    Next b

    MsgBox ("Amount of correct answers: ") & Str(g)

End Sub

Solution

  • Use:

    g = g + 1
    

    For correct and remove the g = b - 1 from the wrong as you do not want to increase g at all.

    Also you need to dim g as a number not a string

    Dim g as Long
    

    And

    Dim b, e, f, s1, s2 As Byte

    only will declare s2 as a Byte the others will be Variant.

    Use:

    Dim b As Byte, e As Byte, f As Byte, s1 As Byte, s2 As Byte
    

    Sub Main2()
    
        Dim b As Byte, e As Byte, f As Byte, s1 As Byte, s2 As Byte
        Dim g As Long
    
        g = 0
        For b = 1 To 5
    
            e = Round(Rnd() * 10)
            f = Round(Rnd() * 10)
            MsgBox ("Count: ") & cStr(e) & (" * ") & cStr(f)
            s1 = InputBox("What's the result?")
    
            s2 = e * f
    
            If s1 = s2 Then
                MsgBox ("Correct")
                g = g + 1    
            Else
                MsgBox ("Incorrect! Right answer is") & cStr(s2)
            End If
    
        Next b
    
        MsgBox ("Amount of correct answers: ") & cStr(g)
    
    End Sub