1

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

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

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

4

1 回答 1

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直接从您的示例代码片段中借用它。

于 2012-10-03T00:07:04.360 回答