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

时间:2017-01-05 20:20:05

标签: excel vba excel-vba

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

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范围内的所有值是否为零,然后只显示一个消息框。有什么想法吗?

感谢。

4 个答案:

答案 0 :(得分:3)

您想知道所有值是否为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

答案 1 :(得分:2)

因为这里有无限的方法可以让猫在这里皮肤化。另一种方法。

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.")

答案 2 :(得分:0)

测试:

  1. 范围不包含任何空值
  2. 所有细胞都相同
  3. 功能

    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
    

    测试

    Sub test()
    MsgBox SameRange([d1:d5])
    End Sub
    

答案 3 :(得分:-1)

'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