“阻止如果没有结束如果”错误

时间:2014-02-05 07:10:15

标签: excel vba excel-vba

我收到此代码的编译错误:

Public Sub CommandButton1_Click()
If TextBox1.Text = "log off" Then
Shell "cmd.exe /c shutdown -l", vbHide: TextBox2.Text = "Logging off"
If TextBox1.Text = "shutdown" Then
Shell "cmd.exe /c shutdown -s", vbHide: TextBox2.Text = "Shutting Down"
If TextBox1.Text = "restart" Then
Shell "cmd.exe /c shutdown -r", vbHide: TextBox2.Text = "Restarting"

Else
MsgBox "Command Not Defined",vbCritical
End Sub

现在它出现了“Block If If End End If”的错误消息。 为什么呢?

1 个答案:

答案 0 :(得分:7)

您错过了End If

Public Sub CommandButton1_Click()
    If TextBox1.Text = "log off" Then
        Shell "cmd.exe /c shutdown -l", vbHide: TextBox2.Text = "Logging off"
    ElseIf TextBox1.Text = "shutdown" Then
        Shell "cmd.exe /c shutdown -s", vbHide: TextBox2.Text = "Shutting Down"
    ElseIf TextBox1.Text = "restart" Then
        Shell "cmd.exe /c shutdown -r", vbHide: TextBox2.Text = "Restarting"
    Else
        MsgBox "Command Not Defined", vbCritical
    End If
End Sub

实际上,在您的代码中,TextBox2.Text始终等于"Restarting"。这就是你应该使用ElseIf声明的原因。

您也可以使用Select Case语句:

Public Sub CommandButton1_Click()
    Select Case TextBox1.Text
        Case "log off"
            Shell "cmd.exe /c shutdown -l", vbHide: TextBox2.Text = "Logging off"
        Case "shutdown"
            Shell "cmd.exe /c shutdown -s", vbHide: TextBox2.Text = "Shutting Down"
        Case "restart"
            Shell "cmd.exe /c shutdown -r", vbHide: TextBox2.Text = "Restarting"
        Case Else
            MsgBox "Command Not Defined", vbCritical
    End Select
End Sub