简体   繁体   中英

I'm Working with a button command, but can't see what's wrong with this code using elseif statements

What this code is supposed to do is that if you have a number in cell 2,2 and it's between a range of those if statements, it will give you a number in cell 3,3 . The problem is that it only works on the first 3 statements. The fourth one doesn't work. It gives you number 1 instead of number 2.

*note: the program uses more statements but this is just to show that the problem is after the third statement, and sorry for my English.

Cell 3,6= 5

Cell 3,7= 10

'MEC
If sheet1.Cells(2, 2) = Empty Then
            sheet3.Cells(3, 3) = ""
            sheet4.Cells(3, 3) = 0

'MEC limited
ElseIf sheet2.Cells(2, 2) = 1 Then
    sheet3.Cells(3, 3) = 0

'MEC aceptable
ElseIf sheet1.Cells(2, 2) > 1 < sheet.Cells(3, 6) Then
    sheet3.Cells(3, 3) = 1

'MEC Good
ElseIf sheet1.Cells(2, 2) > 5 <= sheet2.Cells(3, 7) Then
    sheet3.Cells(3, 3) = 2                 
End If

End Sub

You had a typo in your sheets for 'MEC Aceptable. sheet.Cells . Judging by the context, it looks like it should be Sheet2.Cells

ElseIf sheet1.Cells(2, 2) > 1 < sheet.Cells(3, 6) Then

In addition to that, try using Select Case . You can use IF statements, but Select Case gets handy when you have many ElseIf s

Select Case (Sheet1.Cells(2, 2).Value)

    Case Is = ""
        Sheet3.Cells(3, 3) = ""
        Sheet4.Cells(3, 3) = 0
    Case Is = 1
        Sheet3.Cells(3, 3) = 0
    Case Is <= Sheet2.Cells(3, 6) 'There was typo in your orig code.. Sheet2?
        Sheet3.Cells(3, 3) = 1
    Case Is <= Sheet2.Cells(3, 7)
        Sheet3.Cells(3, 3) = 2

End Select

It would appear that you have a couple of languages confused here. The VBA method of writing the third and fourth comparisons is closer to,

If Sheet1.Cells(2, 2) = Empty Then
            Sheet3.Cells(3, 3) = ""
            Sheet4.Cells(3, 3) = 0
'MEC limited
ElseIf Sheet2.Cells(2, 2) = 1 Then
        Sheet3.Cells(3, 3) = 0
'MEC aceptable
ElseIf Sheet1.Cells(2, 2) > 1 And Sheet1.Cells(2, 2) < Sheet2.Cells(3, 6) Then
        Sheet3.Cells(3, 3) = 1
'MEC Good
ElseIf Sheet1.Cells(2, 2) > 5 And Sheet1.Cells(2, 2) <= Sheet2.Cells(3, 7) Then
        Sheet3.Cells(3, 3) = 2
End If

There is still some priority in these statements. If B2 is 6 then it is greater than 1 and greater than 5. Depending on what is in F3 and G3, the fourth condition may never be reached. Given your example of F3 being 5 it should be OK.

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