我不能让这个循环停下来

时间:2013-10-09 00:33:12

标签: vb.net

我为我的一个类创建了这个循环,但由于某种原因,循环不会停止。 这是我的代码

    Dim strScore As String
    Dim intNumTests As Integer 'counter
    Dim sngSumTests As Single 'accumulator
    Dim sngAverage As Single

    strScore = InputBox("Enter the score. Click cancel when finished.", "Score Entry")

    Do While strScore <> " "
        intNumTests = intNumTests + 1     ' update Counter
        sngSumTests = sngSumTests + Val(strScore)
        strScore = InputBox("Enter the score. Click cancel when finished.", "Score Entry")
    Loop

1 个答案:

答案 0 :(得分:2)

要使循环停止,您必须在InputBox中键入一个空格,而不是实际的单词space,而是按空格键一次。

而不是

Do While strScore <> " "

你真正想要的是

Do While strScore <> "" AndAlso strScore <> " "

Do While strScore.Length <> 0 AndAlso strScore <> " "

现在Cancel按钮将正常工作,如果您没有输入任何内容,它会继续运行,然后按OK按钮。

如果您按下InputBox中的OK按钮并且输入为空,它将返回" "(空格)。
如果按下InputBox中的Cancel按钮,它将返回""(空字符串)

编辑: 原来在.NET Framework 4中使用空的InputBox按OK也会返回(空字符串)所以这是不可能的?检测Cancel按钮。