我正在使用按钮命令,但无法使用 elseif 语句查看此代码有什么问题

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

这段代码应该做的是,如果你在 cell 2,2 中有一个数字,并且它在这些 if 语句的范围之间,它会给你一个 cell 3,3 中的数字。问题是它只适用于前 3 个语句。第四个不行。它给你数字 1 而不是数字 2。

*注意:程序使用了更多的语句,但这只是为了说明问题出在第三条语句之后,对不起我的英语。

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

看来您在这里混淆了几种语言。 VBA写第三次和第四次比较的方法比较接近,

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

这些语句中仍有一些优先级。如果 B2 为 6,则它大于 1 且大于 5。根据 F3 和 G3 中的内容,可能永远不会达到第四个条件。鉴于您的 F3 为 5 的示例,它应该没问题。

您的工作表中有“MEC 可接受”的拼写错误。 sheet.Cells。从上下文来看,应该是Sheet2.Cells

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

除此之外,请尝试使用 Select Case。您可以使用 IF 语句,但是当您有许多 ElseIfs

Select Case 会很方便
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