比较两个范围而不是将相似的细胞复制到另一个范围

时间:2018-03-06 15:48:48

标签: excel-vba vba excel

我有两个包含数字的范围。我希望范围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

1 个答案:

答案 0 :(得分:1)

认为这样做你想要的。您不希望事先定义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