在条件vba中结束while循环

时间:2016-01-14 10:13:36

标签: excel vba excel-vba

我有一个while循环,当我希望它结束​​时,我似乎无法结束。

在此代码中:

row = 3

While Cells(row, COL_B) <> ""

    If Not Cells(WBSrow, COL_B).Value = Mid(Cells(row, COL_E), 1, 8) Then

            valueup = Cells(row, COL_E)

            With Range("C1:C400")
                Set c = .Find(valueup, LookIn:=xlValues)
                If c Is Nothing Then
                    Msgbox "Error in Column E"
                End If
            End With


    End If

row = row + 1

Wend

我想在Ms语句中添加Wend,在If语句中如果条件满足则结束循环。由于用户将输入许多行,因此可能存在多个相同类型的错误,然后msgbox将弹出X次。

我遇到的问题是,如果我把它放在那里,我会得到“Wend without While”错误。我以前用For Each循环做过这个,为什么它不适合我在这里做任何想法?

提前致谢 /吉姆

3 个答案:

答案 0 :(得分:1)

你能否使用Do While ...

例如,这将提前退出循环...

Sub Test()

Dim i As Integer
Do While i < 100
    i = i + 1
    If i = 10 Then Exit Do
Loop

End Sub

答案 1 :(得分:1)

在msgbox之后添加转到语句。因此,当条件满足时,它将执行goto语句并退出循环。我想这会对你有帮助。

row = 3
While Cells(row, COL_B) <> ""
    If Not Cells(WBSrow, COL_B).Value = Mid(Cells(row, COL_E), 1, 8) Then
            valueup = Cells(row, COL_E)
            With Range("C1:C400")
                Set c = .Find(valueup, LookIn:=xlValues)
                If c Is Nothing Then
                    Msgbox "Error in Column E"
                    ''''''''''''''''''''''''''
                    Goto Alldone
                    ''''''''''''''''''''''''''
                End If
            End With
    End If
row = row + 1
Wend
''''''''''''''''''''''''''''''''''''''''''''''
AllDone:
''''''''''''''''''''''''''''''''''''''''''''''

答案 2 :(得分:0)

While..Wend构造没有退出功能,但Do While..Loop子句有:

row = 3

'Add a Do here
Do While Cells(row, COL_B) <> ""

If Not Cells(WBSrow, COL_B).Value = Mid(Cells(row, COL_E), 1, 8) Then

        valueup = Cells(row, COL_E)

        With Range("C1:C400")
            Set c = .Find(valueup, LookIn:=xlValues)
            If c Is Nothing Then
                Msgbox "Error in Column E"
               'Add an Exit Do here
               Exit Do
            End If
        End With
End If

row = row + 1
'Change Wend to Loop here
Loop