检查一个范围内的所有值是否相同

当我的电子表格范围内的所有值都为零时,我需要显示一个消息框。 目前我正在使用下面的代码:

Dim Cell As Range For Each Cell In Range("E17:E25") If Cell.Value = "0" Then MsgBox ("If hardware is required, please manually populate the corresponding sections.") End If Next 

显示消息,但显示9次(对于范围中的每个单元格)。 我需要的是检查E17:E25范围内的所有值是否为零,然后只显示一个消息框。 有任何想法吗?

谢谢。

你想知道所有的值是否为0? 你可以做

If WorksheetFunction.Sum(Range("E17:E25")) = 0 Then MsgBox ("If hardware is required, please manually populate the corresponding sections.")

不需要循环。

编辑:如果你想检查任何其他号码 ,如果所有单元格都是这个数字,你可以这样做:

 Sub t() Dim rng As Range Dim myNum as Long myNum = 1 Set rng = Range("B3:B6") If WorksheetFunction.CountIf(rng, myNum) = rng.Count Then MsgBox ("All the same!") End Sub 

而在这里有无数的方法去皮肤猫是另一种方法。

 Dim Cell As Range Dim ZeroCount As Integer Dim CellCount As Integer ZeroCount = 0 CellCount = 0 For Each Cell In Range("E17:E25") CellCount = CellCount + 1 If Cell.Value = 0 Then ZeroCount = ZeroCount + 1 Next Cell If ZeroCount = CellCount Then MsgBox ("If hardware is required, please manually populate the corresponding sections.") 

为了testing:

  1. 范围不包含任何空值
  2. 所有的细胞都是一样的

function

 Function SameRange(rngIn As Range) As Boolean If Application.CountA(rngIn) = rngIn.Cells.Count Then SameRange = (Application.CountIf(rngIn, rngIn.Cells(1).Value) = rngIn.Cells.Count) End Function 

testing

 Sub test() MsgBox SameRange([d1:d5]) End Sub 
 'something like this Dim isDataPresent as boolean isDataPresent = true for each Cell in Range(....) if cell.value = "0" then isDataPresent = false exit for end if next if not isDataPresent then show message box here end if