Excel 比较两个区域,然后将相似的单元格复制到另一个区域

Excel 比较两个区域,然后将相似的单元格复制到另一个区域,excel,vba,Excel,Vba,我有两个包含数字的范围。我希望范围1和范围2之间所有相似和不同的数字都在范围3中复制。我希望我足够清楚 Dim rng1 As Range Dim rng2 As Range Dim rng3 As Range 'the endRng is because the lengh varies Set rng1 = Range("A250:" & endRng1) Set rng2 = Range("B250:" & endrng2

我有两个包含数字的范围。我希望范围1和范围2之间所有相似和不同的数字都在范围3中复制。我希望我足够清楚

    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range

    'the endRng is because the lengh varies

    Set rng1 = Range("A250:" & endRng1)
    Set rng2 = Range("B250:" & endrng2)
    Set rng3 = Range("D250:" & endrng3)

    Dim match As Boolean
    Dim compte As Integer
    match = False
    Dim cell1 As Range
    Dim cell2 As Range

    For Each cell1 In rng2
        For Each cell2 In rng1
            If cell1.Value = cell2.Value Then

                match = True
              'Here I want to copy all similar and distinct value in rng1 and rng2 to rng3

            Else



            End If
        Next cell2
    Next cell1

我想这就是你想要的。您不想预先定义rng3,而是基于两个范围中匹配的值来构建它

Sub x()

Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim endRng1, endRng2

'the endRng is because the lengh varies

Set rng1 = Range("A250:" & endRng1)
Set rng2 = Range("B250:" & endRng2)
'Set rng3 = Range("D250:" & endrng3)

Dim compte As Long
Dim cell1 As Range
Dim cell2 As Range

For Each cell1 In rng2
    For Each cell2 In rng1
        If cell1.Value = cell2.Value Then
            If rng3 Is Nothing Then
                Set rng3 = cell1
            Else
                Set rng3 = Union(rng3, cell1)
            End If
        End If
    Next cell2
Next cell1

Range("D250").Resize(rng3.Count) = rng3.Value

End Sub

现在的问题是什么?请解释您得到的错误以及在哪一行。我无法获得范围1和范围2之间的相似和不同值,然后将其复制到范围3如果范围1=1,2,3,4范围2=2,4,5范围3必须包含2,4。我试过rng3=cell1.Value,但得到了4,4(在上面的示例中),我明白您想要什么。你的代码做了什么/没有做什么,这是错误的?很高兴它工作了。实际上,使用Match(或Find)更有效,这样可以避免其中一个循环。如果你感兴趣,我可以发布替代代码。