运行宏并结束if语句条件满足

时间:2015-08-10 15:56:23

标签: excel vba excel-vba

我有一个IF Else语句,用于检查工作簿中是否存在电子表格。如果它确实存在,则意味着运行特定的宏,然后停止。如果电子表格不存在,它应该运行到IF语句的末尾,然后生成带有错误消息的MSGBOX。

一旦条件满足,我就无法将IF语句结束,并且宏已经运行。

代码是:

Dim k As Integer
Dim t As String
Dim x As Integer

k = Sheets.Count
x = 1

    While x <= k
        t = Sheets(x).Name
        If t = "Details" Then

            Call Details_1

        Else

            x = x + 1

        End If

    Wend

    If x > k Then

        MsgBox "Something seems to have gone wrong." & vbCrLf & "Please ensure that you have pressed 'Button 1' before you press any of the other buttons", vbOKOnly, "ERROR MESSAGE"

    End If

2 个答案:

答案 0 :(得分:1)

我假设您的意思是调用Details_1,然后继续使用您不想要的While循环。 如果是这样,那么我建议你将代码更改为:

Dim k As Integer
Dim t As String
Dim x As Integer

k = Sheets.Count
x = 1

Do While x <= k
    t = Sheets(x).Name
    If t = "Details" Then

        Call Details_1
        Exit Do

    Else

        x = x + 1

    End If

Loop

If x > k Then

    MsgBox "Something seems to have gone wrong." & vbCrLf & "Please ensure that you have pressed 'Button 1' before you press any of the other buttons", vbOKOnly, "ERROR MESSAGE"

End If

此代码应循环显示工作表,直至找到详细信息,调用Details_1,然后继续下一部分代码

答案 1 :(得分:0)

移动x = x + 1,使其位于第一个End If之后。在调用宏之后,x = x + 1没有被执行,而x总是&lt; = k。