简体   繁体   中英

Using IF AND OR nested statement in VBA

I want to convert an Excel function that I have written to VBA. The Excel function is

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")))))))))))))))

How to create nested IF, AND, OR and nested IF, AND, NOT to accomplish this?

I BELIEVE that the following is faithfully replicating the code shown in your question (after adding the missing ) after "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

I suggest you check the logic thoroughly before using it!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM