在VBA中使用IF AND OR嵌套语句

时间:2016-09-21 00:00:22

标签: excel-vba vba excel

我想将我编写的Excel函数转换为VBA。 Excel功能是

IF(AND(OR(O2="AA",O2="BB",P2<>"CC",P2<>"DD",P2<>"EE",P2<>"FF",P2<>"GG"),"A",
IF(AND(O2="HH",P2<>"II",P2<>"JJ",P2<>"KK"),"B",IF(OR(P2="LL",P2="MM",P2="NN",
P2="OO"),"C",IF(O2="PP","D",IF(O2="QQ","E",IF(O2="RR","F",IF(O2="SS","G",
IF(P2="TT","H",IF(O2="UU","I",IF(AND(O2="VV",P2<>"XX"),"J",IF(AND(O2="YY",
P2<>"ZZ",P2<>"AAA",P2<>"BB",P2<>"CCC",P2<>"DDD",P2<>"EEE"),"K",IF(OR(P2="FFF",
P2="GGG",P2="HHH",P2="III"),"L",IF(O2="JJJ","M",IF(O2="KKK","N",IF(O2="LLL","O",
"NULL")))))))))))))))

如何创建嵌套的IF,AND,OR和嵌套的IF,AND,不是为了完成这个?

1 个答案:

答案 0 :(得分:1)

相信以下内容忠实地复制了您问题中显示的代码(在)之后添加缺失的"BB"之后):

Dim O2 As String
Dim P2 As String
Dim Q2 As String
Dim r As Long

With ActiveSheet
    For r = 2 To .Cells(.Rows.Count, "O").End(xlUp).Row
        O2 = CStr(.Cells(r, "O").Value)
        P2 = CStr(.Cells(r, "P").Value)
        Select Case True
            Case (O2 = "AA" Or O2 = "BB") And P2 <> "CC" And P2 <> "DD" And P2 <> "EE" And P2 <> "FF" And P2 <> "GG"
                Q2 = "A"
            Case O2 = "HH" And P2 <> "II" And P2 <> "JJ" And P2 <> "KK"
                Q2 = "B"
            Case P2 = "LL" Or P2 = "MM" Or P2 = "NN" Or P2 = "OO"
                Q2 = "C"
            Case O2 = "PP"
                Q2 = "D"
            Case O2 = "QQ"
                Q2 = "E"
            Case O2 = "RR"
                Q2 = "F"
            Case O2 = "SS"
                Q2 = "G"
            Case P2 = "TT" ' ??? P2??
                Q2 = "H"
            Case O2 = "UU"
                Q2 = "I"
            Case O2 = "VV" And P2 <> "XX"
                Q2 = "J"
            Case O2 = "YY" And P2 <> "ZZ" And P2 <> "AAA" And P2 <> "BB" And P2 <> "CCC" And P2 <> "DDD" And P2 <> "EEE" 'Warning "BB" here is probably different to "BB" on an earlier line
                Q2 = "K"
            Case P2 = "FFF" Or P2 <> "GGG" Or P2 = "HHH" Or P2 = "III"
                Q2 = "L"
            Case O2 = "JJJ"
                Q2 = "M"
            Case O2 = "KKK"
                Q2 = "N"
            Case O2 = "LLL"
                Q2 = "O"
            Case Else
                Q2 = "NULL"
        End Select
        .Cells(r, "Q").Value = Q2
    Next r
End With

我建议您在使用之前彻底检查逻辑!!