Run-time error '13': Type mismatch on IF combined with OR statement

前端 未结 2 976
借酒劲吻你
借酒劲吻你 2020-12-12 01:34

In my VBA code using excel I have

Dim Field2 As String

Field2 = Cells(i, 4).Value

If Right(Field2, 3) = (\"A-1\" Or \"A-2\" Or \"B-1\" Or \"B-2\" Or \"C-1         


        
2条回答
  •  抹茶落季
    2020-12-12 02:18

    Try this

    If Right(Field2, 3) = "A-1" Or _
       Right(Field2, 3) = "A-2" Or _
       Right(Field2, 3) = "B-1" Or _
       Right(Field2, 3) = "B-2" Or _
       Right(Field2, 3) = "C-1" Or _
       Right(Field2, 3) = "C-2" Or _
       Right(Field2, 3) = "D-1" Or _
       Right(Field2, 3) = "D-2" Or _
       Right(Field2, 3) = "D-3" Then
          Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads"
    End If
    

    Or better still... this

    Select Case Right(Field2, 3)
    Case "A-1","A-2","B-1","B-2","C-1","C-2","D-1","D-2","D-3"
        Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads"
    End Select
    

    Note: I am assuming that i is a valid row number

    Explanation:

    When comparing using an If statement, you cannot say If A = B or C. You are supposed to compare is separately. If A = B or A = C Then. Here each OR is its own Boolean statement i.e it will be evaluated separately.

    When you have multiple such comparisons, it is better to use a Select Statement as shown in the example above.

提交回复
热议问题