调用另一个代码

我正试图找出另一种方式来写这一行。 目前,我有它的范围,如果任何范围AA2:AA7 = 1然后调用代码OneLineItem。 问题是,我需要设置的参数是,如果这些单元格中只有一个等于1,并且只有另一个单元格大于1,例如AA2 = 1,AA7 = 200(例如)。 我遇到的一个问题是AA2 = 1,AA3 = 100,AA7 = 200.但是我只需要一个单元格等于1,另一个单元格大于1,其他所有单元格都是0.如果满足这个条件,然后调用代码OneLineItem。 谢谢。

If ActiveSheet.Range("AA2") = 1 Or ActiveSheet.Range("AA3") = 1 Or ActiveSheet.Range("AA4") = 1 Or ActiveSheet.Range("AA5") = 1 Or ActiveSheet.Range("AA6") = 1 Or _ ActiveSheet.Range("AA7") = 1 Then Call OneLineItem Else 

有6个数字如此:

  • 1应该是1
  • 1应该大于1
  • 4应该是0

所以我们可以使用COUNTIF()来查找它是否遵循这个模式

 Dim OneTrue As Boolean Dim MoreTrue As Boolean Dim RestTrue As Boolean RestTrue = Application.WorksheetFunction.CountIf([AA2:AA7], 0) = 4 [AA2:AA7].Cells.Count - 2 OneTrue = Application.WorksheetFunction.CountIf([AA2:AA7], 1) = 1 MoreTrue = Application.WorksheetFunction.CountIf([AA2:AA7], ">1") = 1 If RestTrue And OneTrue And MoreTrue Then Call OneLineItem End If 

另一种方法是嵌套IF:

 IF Application.WorksheetFunction.CountIf([AA2:AA7], 0) = [AA2:AA7].Cells.Count - 2 Then IF Application.WorksheetFunction.CountIf([AA2:AA7], 1) = 1 Then 'we do not need the third, If the others are true then the last must be true. 'Unless you can have negative numbers. Then you can add the third. Call OneLineItem End If End If 

第二个好处就是只有COUNTIF才有必要,直到find一个假的回报,那么它就不再做了。 而第一个不pipe做什么都是三个。