【问题标题】:Comparing two columns in Excel VBA (greater/less than or equal to)比较 Excel VBA 中的两列(大于/小于或等于)
【发布时间】:2012-10-02 23:57:46
【问题描述】:

我真的很惊讶我很难找到答案。我有 2 列包含一堆数字(在同一个工作表上)。我只是想让代码对列中的每一行说“如果第 1 列中的值 > 第 2 列中的值,请执行此操作”。我试过了

If sheet.range("B2:B35").Value > sheet.range("C2:C35").Value Then
'do something
End If

但显然它不是那样工作的。

【问题讨论】:

  • 我相信你需要依次检查每一对元素..但我不接触 Excel,更不用说 VBA :)
  • 是的,因为第 2 - 35 行中没有一个值代表所有内容

标签: excel function vba compare


【解决方案1】:

您需要考虑一个循环来独立检查每一行。

这个想法是这样的:

For i = 2 to 35
    If Sheet.Range("B" & i).Value > Sheet.Range("C" & i).Value
        'Do Something for Row i
    End If
Next

Value 可以省略,因为它是隐式的,这意味着Sheet.Range("B" & i).Value 返回与Sheet.Range("B" & i) 相同的结果

此外,根据您的需要,有多种方法可以寻址单元格。

  Range() 'Can be used to address multiple cells at the same time over a range
          ' or used to address a single cell as is done here

  Cells() 'Can be used to address a single Cell by calling Cells("B" & i) as is 
          ' done above, or can reference the row and column numerically like  
          ' Cells(2, i)

如果您希望在给定的工作表中移动,则上述任何一种方法都可以与Offset() 结合使用,例如:

  Cells(2, 1).Offset(0, i) 'Addresses the Cell offset from "B1" by 0 columns and
                           ' i rows.  

在这些情况下,我个人倾向于使用 Cells(2, i),但我只是使用了 Range,因为我直接从您的示例代码 sn-p 中借用了它。

【讨论】:

  • 确实就是这么简单。叹。谢谢。
  • 你也可以使用Sheet.Cells(i,2).ValueSheet.Cells(i,3),如果这更清楚的话
  • +1 但最好在> 的两边都显式地使用.Value 或在两边都隐式地使用。目前在 LHS 上是显式的,在 RHS 上是隐式的
  • @barrowc 这是一个错字,我在打字时错过了第二个Value。固定的。感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 2012-10-14
  • 2013-05-16
  • 1970-01-01
  • 2011-01-25
  • 2014-04-19
相关资源
最近更新 更多