在VBA中“编译错误:没有if”,找不到它在说什么

时间:2017-08-07 18:04:05

标签: excel vba excel-vba

我对VBA没有多少经验,我正在尝试编写一个后端函数来根据另一个字段的值计算某些字段。我有一堆嵌套的If Then和ElseIf Then语句,并在我的第一个ElseIf上收到错误。这是有问题的块:

mkdir: cannot create directory '/newfolder': Permission denied

我发现这个问题的大多数解决方案都涉及到每次调整后的缩进或确保有足够的End Ifs,但我已经这样做了,问题仍然存在。任何帮助将不胜感激。

编辑2:问题已经解决,只需修改End Ifs直到它起作用。谢谢大家的帮助!

1 个答案:

答案 0 :(得分:2)

每个ElseIf都没有自己的End If

同样适当的缩进有助于发现这些问题。

正确的方法是:

IF ... Then
    'do somthing
ElseIf
    'do somthing
Else
    'do somthing
End If

ElseIfElse是可选的。

ElseIf rCell.Value = "Blueprint" Then
    aCell = Range("DR")
    If aCell.Value = "Yes" Then
        aCell = Range("ER")
        If aCell.Value = "Yes" Then
            PHASEREVIEWCHECKER = True
        ElseIf aCell.Value = "No" Or aCell.Value = "N/A" Or aCell.Value = "Unknown" Then
            PHASEREVIEWCHECKER = False
        End If
    ElseIf aCell.Value = "No" Or aCell.Value = "N/A" Or aCell.Value = "Unknown" Then
        PHASEREVIEWCHECKER = False
    End If
End If

以下是您使用And s

简化的长嵌套ifs
Public Function PHASEREVIEWCHECKER(R As Integer)
Dim rCell As Range

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set rCell = Range("CR")
If rCell.Value = "Initiate" Then
    If Range("DR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Blueprint" Then
    If Range("DR").Value = "Yes" And Range("ER") = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Design" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Build" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" And Range("GR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Test & Train" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" And Range("GR").Value = "Yes" _
        And Range("HR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Deploy & Operate" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" And Range("GR").Value = "Yes" _
        And Range("HR").Value = "Yes" And Range("IR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
End If
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Function