'For'循环行,比较两列

时间:2021-08-10 13:17:29

I have some thing similar to the below code:

我有一些类似于下面的代码:

set SelectionRNG = Range("A1:B10")

for each xrow in SelectionRNG.rows
if xrow.value(1,1) = xrow.value(1,2) do something

What I need to do is compare the two values stored in xrow.

我需要做的是比较存储在xrow中的两个值。

xrow.value(1,1) = xrow.value(1,2)  

doesn't work.

How do I reference each value?

我如何参考每个值?

1 个解决方案

#1


3  

You're after something like this:

你是这样的:

Dim rngSelection    As Range
Dim rngRow          As Range

Set rngSelection = Range("A1:B10")

For Each rngRow In rngSelection.Rows
    If rngRow.Cells(1, 1) = rngRow.Cells(1, 2) Then
        rngRow.Cells(1, 3) = "same"
    Else
        rngRow.Cells(1, 3) = "different"
    End If
Next

Using "Cells" you can specify 1 as the first row (of a row) and then specify the column numbers you want to compare (1 & 2 in this example) before then outputting to the third column.

使用“单元格”可以指定1作为第一行(行),然后指定要比较的列号(在此示例中为1和2),然后输出到第三列。

If you're going to be fancy, you'd have checks on the size/location of the selection to ensure that you have a basis for comparison and a destination.

如果您想要花哨,您可以检查选择的大小/位置,以确保您有比较和目的地的基础。

#1


3  

You're after something like this:

你是这样的:

Dim rngSelection    As Range
Dim rngRow          As Range

Set rngSelection = Range("A1:B10")

For Each rngRow In rngSelection.Rows
    If rngRow.Cells(1, 1) = rngRow.Cells(1, 2) Then
        rngRow.Cells(1, 3) = "same"
    Else
        rngRow.Cells(1, 3) = "different"
    End If
Next

Using "Cells" you can specify 1 as the first row (of a row) and then specify the column numbers you want to compare (1 & 2 in this example) before then outputting to the third column.

使用“单元格”可以指定1作为第一行(行),然后指定要比较的列号(在此示例中为1和2),然后输出到第三列。

If you're going to be fancy, you'd have checks on the size/location of the selection to ensure that you have a basis for comparison and a destination.

如果您想要花哨,您可以检查选择的大小/位置,以确保您有比较和目的地的基础。