0

我有这段代码,我在其中从 Excel 工作表中获取值并根据条件显示结果。

在我的第二个if声明中,我想检查ocell.value < sd11.

在检查完我需要检查接下来的五个连续值是否相等。如果是,则显示结果。

谁能告诉我如何获得接下来五个连续术语的单元格值?我以为我在代码中提到了但它不起作用。

 Sub DoStuff()
   Dim oCell As Range
   sd11 = Range("s11")

   For Each oCell In Range("e4:e48")
       If oCell.Value < sd13 Then
            Range("R2").Value = "Rule 1s voilation"
            End If

        If oCell.Value < sd11 And oCell.Value = oCell.Value + 1 And oCell.Value = oCell.Value + 2 And oCell.Value = oCell.Value + 3 And oCell.Value = oCell.Value + 4 Then
           Range("T5").Value = "Rule 4s voilation"
          End If

   Next
End Sub
4

2 回答 2

3

在这部分代码中:

If oCell.Value < sd11 And oCell.Value = oCell.Value + 1 And oCell.Value = oCell.Value + 2 And oCell.Value = oCell.Value + 3 And oCell.Value = oCell.Value + 4 Then
      Range("T5").Value = "Rule 4s voilation"
End If

给定 oCell.Value 为 6 和 sd11 值为 11 ,您实际上是在问

If 6 < 11 And 6 = 7 And 6 = 8 And 6 = 9 And 6 = 10 Then
    Range("T5").Value = "Rule 4s voilation"
End If

因为 Range (Cell) 的 Value 属性返回与该单元格关联的值。

由于这种逻辑是无意义的,我认为错误在于您理解如何在 VBA 中使用 Excel 对象的方式,鉴于您是 VBA 的新手,我假设您正在尝试查看值在 oCell 正下方的 5 行中的任何一行都等效于 oCell。这可以通过使用偏移功能引用单元格本身来完成,就像这样。

' i used Or because I thought it might be more what you want. Change to AND if you require all 5 cells to be equal to oCell
    If oCell.Value < sd11 Then
        If oCell.Value = oCell.Offset(1).Value Or oCell.Value = oCell.Offset(2).Value Or oCell.Value = oCell.Offset(3).Value or oCell.Value = oCell.Offset(4).Value or oCell.Value = oCell.Offset(5).Value Then
            Range("T5").Value = "Rule 4s voilation"
        End If
    End If
于 2012-06-18T19:43:40.920 回答
0

科学地做:

if WorksheetFunction.AveDev(oCell.Resize(5)) = 0 then...

于 2012-06-18T19:37:11.797 回答