VBA抛出'else without if'错误

时间:2011-10-02 10:09:20

标签: excel vba if-statement

我正在尝试以下代码,并且它反复抛出'else if if'和类似的错误。我只是不知道错误在哪里,因为每个if都被正确终止。

以下是代码:

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

2 个答案:

答案 0 :(得分:8)

乍一看,If看起来还不错,但我注意到Do的两个Loop都没有找到。

它应该是这样的:

Do While varHRA < salary
    'Do Stuff
Loop

Exit Do用于在While后面的条件为真之前退出循环,但您始终需要Loop关键字。

如果问题仍然存在,请发布您收到的确切错误消息。


编辑:

我只是尝试在MS Access中重现您的VBA中的问题(我没有在此计算机上安装Excel,只有Access):

Public Function Test()

    If 1 = 0 Then

        Do While 1 = 0

            Stop

        Exit Do

    Else

        Stop

    End If

End Function

这段简单的代码给了我完全相同的错误信息:

  

编译错误:没有If

当我用Exit Do替换Loop时,错误就会消失并且代码会编译。

因此,您应该在代码中将Exit Do替换为Loop

答案 1 :(得分:2)

看起来您使用'退出操作'而不是'循环'。 'Exit Do'将退出Do循环,这是你想要这样做的方式吗?