如果为false则断开循环

时间:2018-06-01 20:40:17

标签: excel vba excel-vba

我将在Excel上有一组数据,用户将按下一个按钮,它将附加在SQL表上。这只会发生,并且仅在验证列(比如列C)全部为true时才会发生。

如果验证列中只有一个false,则代码应该停止并且不会执行sql语句。

示例,下表应该允许执行SQL代码并将其附加在SQL表:

Name    Age Validation
John    25  TRUE
Jane    33  TRUE
Eniola  39  TRUE
Alex    23  TRUE
Dave    22  TRUE
Tom     30  TRUE
Kat     23  TRUE
Kim     37  TRUE

由于验证列上有false,因此不应执行下表:

Name    Age Validation
John    25  TRUE
Jane    33  TRUE
Eniola  39  TRUE
Jon     42  FALSE
Dave    22  TRUE
Tom     30  TRUE
Kat     23  TRUE
Kim     37  TRUE

为此,我认为最有效的方法是设置For Loop以通过C列检查所有值是true

我尝试使用以下代码执行此操作:

    Dim i as Long
    For i = 1 to Rows.count
    If Cells(i, 1).Value = False Then
    msgbox("unable to execute")
    End If
    Next i
    ------ code to execute SQL command -------

如果列中有false,我不确定如何破解代码。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

您需要Exit For

Dim i As Long
For i = 1 To Rows.Count
    If Cells(i, 1).Value = False Then
        MsgBox ("unable to execute")
        Exit For
    End If
Next i

评论后更新

Dim i As Long
For i = 1 To Rows.Count
    If Cells(i, 1).Value = False Then
        MsgBox ("unable to execute")
        Exit For
    Else
        ' Do the sql command here, if you want it once per row until a False if found
    End If
Next i
' Do the sql command here if you only run it once after the loop

答案 1 :(得分:2)

Dim i as Long
For i = 1 to Rows.count
     If Cells(i, 1).Value = False Then
          msgbox("unable to execute")
          GoTo FailedCheck
     End If
Next i

'execute sql

FailedCheck:

'Code resume here without running sql

重要的是要注意,使用这种方法虽然功能强大,但有时会很危险。尽量避免使用它。可以像这样重写

Dim i as Long, chk as boolean
chk = True
For i = 1 to Rows.count
     If Cells(i, 1).Value = False Then
          msgbox("unable to execute")
          chk = False
          Exit For
     End If
Next i

If chk = true Then 'execute sql