在VBA中获得连续单元格的价值

我有这个代码,我从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 

在这部分代码中:

 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 

科学地做:

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