0

I'm getting a compile error for this code:

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

Now it comes up with this Error Message of "Block If without End If". Why?

1
  • 1
    what you're doing is self terminating IF statement by putting the condition and result in one line. the last Else is floating since all IF statements above already terminated. @simoco already showed the alternative. Commented Feb 5, 2014 at 7:57

1 Answer 1

8

You have missed 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

Actually in your code you will always have TextBox2.Text equals to "Restarting". That's why you should use ElseIf statement.

You could use Select Case statement as well:

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
Sign up to request clarification or add additional context in comments.

1 Comment

+ 1 for also suggesting select case :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.