如何在Excel中嵌套IF,AND,OR

时间:2014-04-22 08:19:27

标签: excel vba logical-operators formulas nested-if

excel公式中缺乏清晰易读的格式对我来说非常困难。

我需要写一个公式:

  • 检查J2是否为"否"
  • 如果不是,请将值设置为" N / A"
  • 如果是,请在E2中查看指定日期的日期
  • 如果在给定日期之后,将值设置为" Pass"
  • 如果在给定日期之前,检查G2是否为"取消"并且K2是" No"或者G2是" Void"和K2是"是"
  • 如果true设置值为"失败"
  • 如果错误设置值为"通过"

如果我使用Javascript,它可能看起来像这样:

function formulasMakeMyHeadHurt(J2,E2,G2,K2,givenDate){

    if(J2=="No"){
        if(E2>givenDate){
            if((G2=="Cancel"&&K2!="No")||(G2=="Void"!="Yes")){
                return "Fail"
            }
            else return "Pass"
        }
        else return "Pass"
    }
    else return "N/A"
}

这是我尝试过的,至少有一个语法错误,更不用说一些可能的逻辑问题了。我在编写时尝试了不同方式格式化公式,但我不断迷失在括号中,无法找出原因。

=IF( ISNUMBER(SEARCH(J20,"No"))
           , IF($E20>=DATE(2014,4,10))
               ,"Pass"
           , IF(      OR(   ISNUMBER(FIND("Void",G20))    ,   AND(ISNUMBER(FIND("Cancel",G20)), ISERROR(SEARCH("No",K20)))    )    )
                          ,"Pass"
            ,"Fail")
                )
,"N/A")

相同的公式没有间距,如果你的眼睛更容易:

=IF( ISNUMBER(SEARCH(J20,"No")),IF($E20>=DATE(2014,4,10)),"Pass", IF(OR(ISNUMBER(FIND("Void",G20)),AND(ISNUMBER(FIND("Cancel",G20)),ISERROR(SEARCH("No",K20))))),"Pass","Fail")),"N/A")
  • 如何编写此公式?
  • 使用VBA脚本会更好吗?

1 个答案:

答案 0 :(得分:2)

根据您的描述,这是公式:

=IF(ISNUMBER(SEARCH("No",J2)),IF(E2>=DATE(2014,4,10),"Pass",IF(OR(AND(ISNUMBER(SEARCH("Cancel",G2)),ISNUMBER(SEARCH("No",K2))),AND(ISNUMBER(SEARCH("Void",G2)),ISNUMBER(SEARCH("Yes",K2)))),"Fail","Pass")),"N/A")

或者如果您愿意,可以使用此UDF:

Function formulasMakeMyHeadHurt(J2 As String, E2 As String, _
                            G2 As String, K2 As String, _
                            givenDate As Date) As String
    Dim res As String

    If J2 Like "*No*" Then
        If CDate(E2) >= givenDate Then
            If (G2 Like "*Cancel*" And K2 Like "*No*") Or _
                (G2 Like "*Void*" And K2 Like "*Yes*") Then
                res = "Fail"
            Else
                res = "Pass"
            End If
        Else
            res = "Pass"
        End If
    Else
        res = "N/A"
    End If

    formulasMakeMyHeadHurt = res
End Function

然后在任何单元格中调用它:=formulasMakeMyHeadHurt(J2,E2,G2,K2,DATE(2014,4,10))