Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 804
Chinmay Kamat Avatar asked May 08 '26 21:05

Chinmay Kamat


2 Answers

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.

like image 110
Christian Specht Avatar answered May 11 '26 14:05

Christian Specht


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?

like image 21
Pwaddles Avatar answered May 11 '26 13:05

Pwaddles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!