繁体   English   中英

Excel VBA 循环中的多个 if 语句工作不正确

[英]Excel VBA Multiple if statement in loop working incorrectly

如果已经涵盖了,请提前道歉,我确实尝试先环顾四周。

我在一个循环中有多个 if 语句,并且没有遵守 if 语句的条件。 我正在研究通过管道的流体流动,我的计算条件随着雷诺数介于哪个数字范围而变化。

no-slip Reynolds < 2000 是层流 no-slip Reynolds > 4000 是湍流 between is transition

我将所有三个条件都放在它们自己的列中,if 语句应该根据雷诺数选择正确的条件,然后沿着工作表中的所有行向下移动。

        For i = 6 To rows + 6 Step 1
            
            If Range("BQ" & i).Value <=2000 Then
                Range("BV" & i).Value = Range("BR" & i).Value
            End If
            If Range("BQ" & i).Value >= 4000 Then
                Range("BV" & i).Value = Range("BT" & i).Value
            End If
            If 2000 < Range("BQ" & i).Value < 4000 Then
                Range("BV" & i).Value = Range("BU" & i).Value
            End If
        Next i

结果:

Excel表格

正如您所看到的,即使雷诺数低于 2000,Fns 列也会被 Fns Transition 填充。

从我的评论中删除:

2000 < Range("BQ" & i).Value AND Range("BQ" & i).Value < 4000代替。 否则,您最终会解决不等式范围的一半( True < 4000 ),然后将生成的布尔值与 4000 进行比较,这将始终为True (我认为)。 此外, if您应该在这里使用elseif而不是 separate ,因为一次只能有一个条件为真。

    For i = 6 To rows + 6 Step 1            
        If Range("BQ" & i).Value <=2000 Then
            Range("BV" & i).Value = Range("BR" & i).Value
        ElseIf Range("BQ" & i).Value >= 4000 Then
            Range("BV" & i).Value = Range("BT" & i).Value
        ElseIf 2000 < Range("BQ" & i).Value AND Range("BQ" & i).Value < 4000 Then
            Range("BV" & i).Value = Range("BU" & i).Value
        End If
    Next i

如果使用 Select Case 语句,您可能会更幸运:

Select Case Range("BQ" & i).Value
    Case Is <= 2000
        Range("BV" & i).Value = Range("BR" & i).Value
    Case Is >= 4000
        Range("BV" & i).Value = Range("BT" & i).Value
    Case Else
        Range("BV" & i).Value = Range("BU" & i).Value
End Select

这在以后也更容易阅读和调试。 或者 Excel 公式可以做到这一点:

=SWITCH(true,BQ2<=2000,BV2,BQ2>=4000,BT2,BU2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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