Chinmay Kamat
Chinmay Kamat

Reputation: 301

VBA throwing 'else without if' error

I was trying out the following code and its repeatedly throwing the 'else without if' and such similar errors. I just cant figure out where the error lies, because each if is properly terminated.

Here is the code:

Sub hra_macro()

Dim city As Boolean
Dim salary As Integer
Dim varHRA As Integer
Dim mimHRA As Integer
Dim maxHRA As Integer
Dim A As Integer
Dim B As Integer
Dim Rent As Integer

city = Range("b1").Value
salary = Range("b2").Value
Rent = Range("b3").Value

If city = True Then

varHRA = 0

    A = Rent - (salary / 10)
    B = salary * 0.5
    Do While varHRA < salary
        varHRA = varHRA + 1
            If (varHRA < A And varHRA < B) Then
            minHRA = varHRA
            End If
            If (A < varHRA And A < B) Then
            minHRA = A
            End If
            If (B < varHRA And B < A) Then
            minHRA = B
            End If
            If minHRA > maxHRA Then
            maxHRA = minHRA
            End If
    Exit Do
Else '<<<<<<<<<<<<<<<<<<<< PROBLEM AREA

varHRA = 0

    A = Rent - (salary / 10)
    B = salary * 0.4
    Do While varHRA < salary
        varHRA = varHRA + 1
        If (varHRA < A And varHRA < B) Then
        minHRA = varHRA
        End If
        If (A < varHRA And A < B) Then
        minHRA = A
        End If
        If (B < varHRA And B < A) Then
        minHRA = B
        End If
    If minHRA > maxHRA Then
    maxHRA = minHRA
    End If
    Exit Do
End If

Range("b4").Value = maxHRA

End Sub

Upvotes: 2

Views: 2763

Answers (2)

Christian Specht
Christian Specht

Reputation: 36451

The Ifs look okay to me at first glance, but I noticed that both Dos are missing the Loop.

It should look like this:

Do While varHRA < salary
    'Do Stuff
Loop

Exit Do is used to exit the loop before the condition behind the While is true, but you always need the Loop keyword.

If the problem still remains, please post the exact error message that you're getting.


EDIT:

I just tried to reproduce your problem in VBA in MS Access (I don't have Excel installed on this machine, only Access):

Public Function Test()

    If 1 = 0 Then

        Do While 1 = 0

            Stop

        Exit Do

    Else

        Stop

    End If

End Function

This simple piece of code gives me the exact same error message that you got:

Compile error: Else without If

When I replace the Exit Do by a Loop, the error goes away and the code compiles.

So, you should replace the Exit Do by Loop in your code.

Upvotes: 8

Pwaddles
Pwaddles

Reputation: 142

Looks like your using 'Exit Do' instead of 'Loop'. 'Exit Do' will exit the Do loop, is this the way you want this to behave?

Upvotes: 2

Related Questions