比较两列并打印相同的值

时间:2015-10-12 09:33:13

标签: excel vba excel-vba

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

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应用程序定义或对象定义错误

3 个答案:

答案 0 :(得分:0)

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

另外,当您的循环设置时,您可以将第一个数组中的每个单元格与第二个数组中的每个单元格进行比较。你只需要一个公共因子来循环。

我添加了一些测试以避免一些基本问题:

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

答案 1 :(得分:0)

简短的回答是,在使用Cells时需要指定Row和Column。列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

答案 2 :(得分:0)

下面简单介绍一个数组,其中一个范围包含3列(两个用于比较,第三个用于写入结果)

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