VBA进行随机计算并确认正确答案

时间:2018-10-26 13:58:49

标签: vba calculation msgbox

下面的代码为您提供了一个随机计算,您提供了答案,并通过程序检查了答案是否正确。总的来说,您有5个要解决的示例。最后,我想创建一个简单的MsgBox,说明用户正确的实例数-正确答案的数量。

此MsgBox当前由“ g”表示。不幸的是,g = b + 0与g = b-1组合不是正确的方法。

有人可以帮忙吗?谢谢!

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

1 个答案:

答案 0 :(得分:1)

使用:

g = g + 1

为了更正并从错误中删除g = b - 1,因为您根本不想增加g。

另外,您需要将g调暗为数字而不是字符串

Dim g as Long

还有

  

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

仅将s2声明为Byte,其他人声明为Variant

使用:

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