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

Vba 检查范围内的所有值是否相同,vba,excel,Vba,Excel,当电子表格上某个范围内的所有值都为零时,我需要显示一个消息框。目前我正在使用以下代码: 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次(对

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

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?你可以这么做

'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 
如果工作表function.Sum(范围(“E17:E25”)=0,则MsgBox(“如果需要硬件,请手动填充相应的部分”)

不需要循环

编辑:如果要检查任何其他数字,并且如果所有单元格都是该数字,则可以执行以下操作:

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.")
为了检验这一点:

  • 该范围不包含任何空值
  • 所有的细胞都是一样的
  • 作用

    试验


    放弃FOR循环,对范围使用SUM。我最喜欢这种方法,因为它适用于任何特定的值(文本或数字等),但这必须是基于简单性和满足标准的最正确的方法。@CaptainGrumpy-从你上面的问题来看,是的,我认为
    SUM()
    是获取所需内容的最快捷方式。但是,如果要查找
    字符串
    值或任何其他特定数字,则这是一个稍微独立的问题。如果你想知道它们是否都是相同的数字,我认为一个快速的方法就是使用
    CountIf()
    ,看看total
    CountIf()
    结果是否与你范围内的单元格总数相匹配。当然,
    Sum
    方法依赖于所有值都>=0的假设。(但如果是“订单数量”或类似的数字,这可能是一个有效的假设。负数应该会导致错误消息,所以同样的消息可能是好的。)我只是说,如果用户输入的数字是
    4、-5、1、3、2、6、-13、1、1
    ,那么
    和将表示答案为零,即使所有的值都不是零(在这种情况下,没有一个值是零)。说真的,我并不是在寻找任何东西。这不是我的问题。我认为总和一般来说是好的,但从编码的角度来看,YowE3K的观点是更好的做法,除非有明确排除负数的条件。如果所有值都是0,OP想要一个msg。如果有0,则显示msg
    
    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