2012-10-02 381 views
1

实际上我非常惊讶地发现我很难找到答案。我有2列包含一堆数字(在同一工作表上)。我只想让代码说出“如果列1中的值>列2中的值,对列中的每一行都这样做”。我试过比较Excel VBA中的两列(大于/小于或等于)

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

但是显然它不能这样工作。

+1

我相信你需要依次检查每对元素......但我不碰Excel,更不用说VBA :) – 2012-10-03 00:06:24

+0

是的,因为没有表示行中所有内容的单个值2 - 35 –

回答

6

你需要考虑一个循环来检查每一行与其他的独立。

的想法是这样的:

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,因为我从示例代码片段中直接借用了它。

+0

事实确实如此简单。叹。谢谢。 – Kurt

+0

如果这更清晰 – enderland

+0

+1,您也可以使用'Sheet.Cells(i,2).Value'和'Sheet.Cells(i,3)',但是最好在两边都明确指定'.Value' '''或双方隐含。目前有明确的LHS和隐含在RHS – barrowc

相关问题