Mike
Mike

Reputation: 2313

If then statement in vba

I have the following code:

If Label1 = 0 Then
btn1.Enabled = False
ElseIf Label2 = 0 Then
btn2.Enabled = False
ElseIf Label3 = 0 Then
btn3.Enabled = False
ElseIf Label4 = 0 Then
btn4.Enabled = False

End If
End If
End If

End Sub

Right now when it runs after a condition ios true it ends sub. I want all conditions that are true to execute. So right now if Label2 = 0 the button is disabled and the program ends. I want it to continue checking the rest of the Labels. I'm sure it's an else / If Then issue.

Upvotes: 0

Views: 505

Answers (5)

Oneide
Oneide

Reputation: 1020

Just for the sake of listing, here is another possibility:

btn1.Enabled = (Label1 <> 0)
btn2.Enabled = (Label2 <> 0) 
btn3.Enabled = (Label3 <> 0) 
btn4.Enabled = (Label4 <> 0) 

Upvotes: 3

Richard210363
Richard210363

Reputation: 8406

You don't need the ElseIfs.

If you want to test all conditions then test them separately

If Label1 = 0 Then
btn1.Enabled = False
End If
If Label2 = 0 Then
btn2.Enabled = False
End If
If Label3 = 0 Then
btn3.Enabled = False
End If
If Label4 = 0 Then
btn4.Enabled = False
End If

Upvotes: 4

Alain
Alain

Reputation: 27220

You have to change your code to:

If Label1 = 0 Then btn1.Enabled = False
If Label2 = 0 Then btn2.Enabled = False
If Label3 = 0 Then btn3.Enabled = False
If Label4 = 0 Then btn4.Enabled = False

End Sub

Upvotes: 0

Security Hound
Security Hound

Reputation: 2551

Only one of those will happen when you use If-Else If conditional block ( it would be the first one that is true ). If you want each one to happen then use 4 seperate IF conditional statements.

Upvotes: 1

Jonas Heidelberg
Jonas Heidelberg

Reputation: 5024

Don't use ElseIf: Use Separate If/Then/End If structures for all labels.

Upvotes: 0

Related Questions