在函数内部使用“exit for”

Use " exit for " inside a function

我认为这可能是一个非常愚蠢的问题,如果有人能向我解释一下,我将不胜感激。所以在我的程序中,我有 2 个 for 循环,它们都有相同的消息框,询问用户是否真的想停止循环。所以我 tought 创建一个 sub 用于两个 for 循环,所以我不需要在两个 for 循环上写相同的东西,但是因为开始(For i = rect.X To endPointX - 1)和结束for 循环的 (Next) 不存在,我无法在 sub 中写入 "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

感谢关注

你在这里走的是正确的路线,除了你可以通过返回来自你的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 的机器上,但应该会给你想法。