在函数内部使用“退出用于”

时间:2019-10-03 14:54:09

标签: vb.net function for-loop exit

我认为这可能是一个非常愚蠢的问题,如果有人可以向我解释一下,我将非常感激。因此,在我的程序中,我有2个for循环,它们两个都将具有相同的messabox,询问用户是否确实要停止循环。所以我很难创建一个可以在两个for循环上使用的子程序,所以我不需要在两个for循环上都写相同的东西,但是因为开始(对于i = rect.X To endPointX-1)和end(Next )的for循环不存在,我无法在子程序内编写“ exit for”。有办法吗?抱歉,有点混乱。

具有msgbox的循环之一

For j = endpointY - 1 To rect.Y Step -1
    If escPress = True Then
        response = MsgBox(Msg, Style, Title)
        If response = vbYes Then
            Exit For

        ElseIf response = vbNo Then
            escPress = False

        End If
    End If
    If bmp.GetPixel(i, j) = cor Then
        crossIn(PictureBox1, n, pemSize, i, j)
        tempI = i

        Exit For
    End If
 Next

创建的函数:

Public Sub escKeyPress(escpress As Boolean, response As Object, msg As Object, style As Object, title As Object)
    If escpress = True Then
        response = MsgBox(msg, style, title)
        If response = vbYes Then
            Exit For

        ElseIf response = vbNo Then
            escpress = False

        End If
    End If
 End Sub

感谢您的关注

1 个答案:

答案 0 :(得分:2)

您在这里沿正确的路线走,除了可以通过从您的Function中返回 指示结果为vbYes

Public Function escKeyPress(escpress As Boolean, response As Object, msg As Object, style As Object, title As Object) As Boolean
    escKeyPress = False

    If escpress = True Then
        response = MsgBox(msg, style, title)
        If response = vbYes Then
            escKeyPress = True
        End If
    End If
 End Sub

运行escKeyPress = FalseescKeyPress = True设置escKeyPress函数的结果。

在您的for循环中的调用代码中:

For j = endpointY - 1 To rect.Y Step -1
    If escKeyPress(...) Then ' Left these params blank as I don't know what they are
        Exit For
    End If
    If bmp.GetPixel(i, j) = cor Then
        crossIn(PictureBox1, n, pemSize, i, j)
        tempI = i
        Exit For
    End If
Next

这是未经测试的,因为我不在使用VB atm的计算机上,但是应该可以告诉您。