比较两列并打印相同的值

我试图比较两列,如果有任何类似的值,那么我想打印在第三列的价值。 我的代码是这样的:

Sub compare() Dim arr1 As Range Dim arr2 As Range Set arr1 = Range("A1:A6") Set arr2 = Range("B1:B6") For Each x In arr1 For Each y In arr2 If x = y Then Cells(C1).Value = 0 End If Next y Next x End Sub 

我看到:

运行时错误1004应用程序定义的或对象定义的错误

使用For Each处理数组是很棘手的,因为您不知道数组中的数据在哪里。 此外,它只会创build重复的值,您将无法直接与您的数组进行交互。

另外,因为你的循环是集合,你可以将第一个数组中的每个单元格与第二个数组中的每个单元格进行比较。 你只需要一个共同的因素来循环。

我添加了一些testing,以避免一些基本问题:

 Sub compare() Dim arr1 As Range, _ arr2 As Range, _ Ws As Worksheet With Ws Set arr1 = .Range("A1:A6") Set arr2 = .Range("B1:B6") If arr1.Columns.Count > 1 Or arr2.Columns.Count > 1 Then MsgBox "Too many columns for this simple compare", vbCritical + vbOKOnly Exit Sub Else If arr1.Rows.Count <> arr2.Rows.Count Or arr1.Cells(1, 1).Row <> arr2.Cells(1, 1).Row Then MsgBox "The ranges don't have the same amout of lines or don't start at the same line", vbCritical + vbOKOnly Exit Sub Else For i = 1 To arr1.Rows.Count If arr1.Cells(i, 1) <> arr2.Cells(i, 1) Then Else .Cells(arr1.Cells(1, 1).Row + 1, _ Max(arr1.Cells(1, 1).Columns, arr2.Cells(1, 1).Column)) _ .Offset(0, 1).Value = arr1.Cells(i, 1) End If Next i End If End If End With End Sub 

简单的答案是,您需要在使用单元格时指定“行”和“列”。 列C为3,所以显示匹配值的代码应该看起来像这样:

 Sub compare() Dim arr1 As Range Dim arr2 As Range Dim count As Integer Set arr1 = Range("A1:A6") Set arr2 = Range("B1:B6") For Each x In arr1 For Each y In arr2 If x = y Then count = count + 1 Cells(count, 3) = x End If Next y Next x End Sub 

在一个简单的方法下,定义一个有三列的范围(两个比较和第三个写结果)

 Sub compare() Dim Arr() As Variant Arr = Range("A1:C6") Dim R As Long For R = 1 To UBound(Arr, 1) If Arr(R, 1) = Arr(R, 2) Then Arr(R, 3) = 0 'or the value of 1th column like arr(r,1) End If Next R Range("A1:C6") = Arr End Sub