vba 比较Excel VBA中的两列(大于/小于或等于)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12700118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing two columns in Excel VBA (greater/less than or equal to)
提问by Kurt
I'm actually quite surprised that I'm having so much trouble finding as answer for this. I have 2 columns containing a bunch of numbers (on the same worksheet). I simply want to have code to say "If the value in column 1 > the value in column 2, do this" for each row in the columns. I tried
我实际上很惊讶我在寻找这个问题的答案时遇到了很多麻烦。我有 2 列包含一堆数字(在同一个工作表上)。我只是想让代码对列中的每一行说“如果第 1 列中的值 > 第 2 列中的值,则执行此操作”。我试过
If sheet.range("B2:B35").Value > sheet.range("C2:C35").Value Then
'do something
End If
But apparently it doesn't work that way.
但显然它不会那样工作。
回答by psubsee2003
You need to think about a loop to check each row independently of the others.
您需要考虑一个循环来独立于其他行检查每一行。
The idea is something like:
这个想法是这样的:
For i = 2 to 35
If Sheet.Range("B" & i).Value > Sheet.Range("C" & i).Value
'Do Something for Row i
End If
Next
The Value
can be omitted as it is implicit, meaning Sheet.Range("B" & i).Value
returns an identical result as Sheet.Range("B" & i)
在Value
可以省略,因为它是隐式的,这意味着Sheet.Range("B" & i).Value
返回相同的结果作为Sheet.Range("B" & i)
Additionally, there are numerous ways to address a cell depending on your needs.
此外,根据您的需要,有多种方法可以对单元进行寻址。
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)
And either of the above methods can be used in conjunction with Offset()
if you are looking to move around a given worksheet such as:
Offset()
如果您希望在给定的工作表中移动,则可以结合使用上述任何一种方法,例如:
Cells(2, 1).Offset(0, i) 'Addresses the Cell offset from "B1" by 0 columns and
' i rows.
I personally tend to use Cells(2, i)
in these cases, but I just used Range
as I borrowed it straight from your example code snippet.
我个人倾向于Cells(2, i)
在这些情况下使用,但我只是Range
直接从您的示例代码片段中借用了它。