如果单元格值>在那个范围内的任何单元格中为0

时间:2017-12-20 11:59:39

标签: excel vba

我有一个包含x行和y列的表。每个单元格都包含一个数字。通常为0,有时为1或更高。

我有代码提示我确认是否存在任何非零值,然后单步执行一段代码来处理这些值。

我希望更新后的代码能够识别出即使一个单元格的值大于0,也可以进入特定的代码片段。否则,请忽略它。

我尝试使用循环执行此操作,但如果多个单元格的值大于0,则当前代码会多次执行。

无效的伪代码:

For Each cell in Range("B2:C8")
    If cell.value > 0 Then
        "some code"
    End If
Next cell

每次找到非零值时,这将执行“某些代码”,这在任何时候都会出现多个非零值。

4 个答案:

答案 0 :(得分:3)

您只需稍微修改一下代码:

For Each cell in Range("B2:C8")
    If cell.value > 0 Then
        "some code"
        exit for 'Now that we have executed the code once we don't need to run it again!
    End If
Next cell

答案 1 :(得分:3)

我会缩短

if worksheetfunction.sum(Range("B2:C8")) > 0 then 

答案 2 :(得分:0)

据我了解:在第一次出现非零值时,您的代码应该"做某事"并停止搜索另一个非零值。对? 在这种情况下,"退出"应该解决你的问题。

For Each cell in Range("B2:C8")
    If cell.value > 0 Then
        "some code"
        Exit For
    End If
Next cell

答案 3 :(得分:0)

我可能回答这个查询很晚,但是只是将其留在这里以供将来参考。我的方法是使用2个循环,分别用于行和列。这是一个示例答案:

 For icol from col_start to col_end 'column loop 
        For irow from row_start to row_end 'row loop

       Og_val = Activesheet.cells(irow,icol). value

       If og_val > 0 Then 'To check if existing cell value is more than 0

        "Some code"

       End If

      Next irow
   Next icol
相关问题