user2237168
user2237168

Reputation: 303

Elseif is skipped

I have the following in my excel file

+----------+-------+---------------+
|  Option  | value | VisibleOption |
+----------+-------+---------------+
| Option#1 |       | #Option5      |
| Option#2 |       | #Option6      |
| Option#3 |     3 | #Option7      |
| Option#4 |  1200 | #Option8      |
+----------+-------+---------------+

the following function is written

Private Sub CommandButton1_Click()

  Dim i                 As Integer
  Dim value_s           As String

    i = 2
    Do Until IsEmpty(Cells(i, 1))
        value_s = ActiveSheet.Cells(i, 2)

        If value_s <> "" Then
            Debug.Print "value_s is not empty"
        ElseIf value_s = "1200" Then
            Debug.Print "value_s contains a 1200"
        Else
            Debug.Print "print the rest"
        End If

    i = i + 1
    Loop

End Sub

Right now, the function returns the following

print the rest
print the rest
value_s is not empty
value_s is not empty

While it should return something like the following, since a 1200 is present:

print the rest
print the rest
value_s contains a 1200
value_s is not empty
value_s is not empty

It seems, the ElseIf is skipped. What goes wrong here?

Upvotes: 0

Views: 43

Answers (3)

Uroš Grum
Uroš Grum

Reputation: 138

If statement closes after first successful IF, in your instance it would get to elseif only if the value would be empty, in which case it would skip it ... so it would never call that. To fix this exact example, I would switch things around like:

If value_s == "" Then
        Debug.Print "print the rest"
    ElseIf value_s = "1200" Then
        Debug.Print "value_s contains a 1200"
    Else
        Debug.Print "value_s is not empty"
    End If

Better way of doing this would be:

Select Case value_s
    Case ""
        Debug.Print "print the rest"
    Case "1200"
        Debug.Print "value_s contains a 1200"
    Case Else
        Debug.Print "value_s is not empty"
End Select

In this case you can add as many possibilities as you wish.

Upvotes: 1

h2so4
h2so4

Reputation: 1577

I would write the ElseIf instruction like this, I suspect 1200 is stored as a number, and you compare it to the string "1200" which is not the same.

ElseIf value_s = 1200 Then

Upvotes: 1

Vityata
Vityata

Reputation: 43595

Add this to your loop:

debug.print ActiveSheet.Name
debug.print value_s

You will get the results in the immediate window and you can fix accordingly.

Upvotes: 0

Related Questions