实际上我非常惊讶地发现我很难找到答案。我有2列包含一堆数字(在同一工作表上)。我只想让代码说出“如果列1中的值>列2中的值,对列中的每一行都这样做”。我试过比较Excel VBA中的两列(大于/小于或等于)
If sheet.range("B2:B35").Value > sheet.range("C2:C35").Value Then
'do something
End If
但是显然它不能这样工作。
实际上我非常惊讶地发现我很难找到答案。我有2列包含一堆数字(在同一工作表上)。我只想让代码说出“如果列1中的值>列2中的值,对列中的每一行都这样做”。我试过比较Excel VBA中的两列(大于/小于或等于)
If sheet.range("B2:B35").Value > sheet.range("C2:C35").Value Then
'do something
End If
但是显然它不能这样工作。
你需要考虑一个循环来检查每一行与其他的独立。
的想法是这样的:
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
,因为我从示例代码片段中直接借用了它。
我相信你需要依次检查每对元素......但我不碰Excel,更不用说VBA :) – 2012-10-03 00:06:24
是的,因为没有表示行中所有内容的单个值2 - 35 –