2014-02-05 38 views
0

我得到這個代碼的編譯錯誤:「塊如果沒有結束如果」錯誤

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 

現在它的這個錯誤消息「塊如果沒有結束如果」出現。 爲什麼?

+1

你在做什麼是自終止'通過將條件和導致一行IF'聲明。由於上述所有'IF'語句已經終止,所以最後一個'Else'是浮動的。 @simoco已經展示了另一種選擇。 – L42

回答

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 
+2

+ 1也提示選擇情況:) –

相關問題