比较Excel VBA中的两列(大于/小于或等于) [英] Comparing two columns in Excel VBA (greater/less than or equal to)

查看:2401
本文介绍了比较Excel VBA中的两列(大于/小于或等于)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很惊讶,我有这么多麻烦找到答案。我有2列包含一堆数字(在同一工作表上)。我只是想让代码说如果列1中的值>列2中的值,做这个为列中的每一行。我尝试了

 如果sheet.range(B2:B35)。价值然后
'做某事
结束如果

但显然它不工作。

解决方案

你需要考虑一个循环来检查每个

  For i = 2 to 35 
如果Sheet.Range(B& i).Value> Sheet.Range(C& i).Value
'为行执行某项操作
结束如果
接下来

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


相同的结果

此外,根据您的需要,还有许多方法来处理单元格。

  Range可以用于在范围
'的同时寻址多个单元格或用于寻址单个单元格,如这里所做的

Cells()'可用于寻址单个单元格通过调用Cells(B& i)作为
'做上面的操作,或者可以像
一样引用行和列的数字。细胞(2,i)

上述任何一种方法都可以与 Offset()正在寻找围绕给定工作表移动,例如:

 单元格(2,1).Offset(0,i)单元从B1偏移0列和
'i行。

我个人倾向于使用 Cells(2,i)在这些情况下,但我只是使用 Range ,因为我直接从你的示例代码片段。


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

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

But apparently it doesn't work that way.

解决方案

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)

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:

  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.

这篇关于比较Excel VBA中的两列(大于/小于或等于)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆