如何获得不是联合的范围的一部分?

时间:2015-01-20 18:33:16

标签: vba excel-vba excel

我知道我可以写下两个范围的联合:

Dim r1 as range
Dim r2 as range
Union(r1, r2)

但有没有我可以得到r1或r2中的范围而不是联盟?

3 个答案:

答案 0 :(得分:3)

Sub CombinedMinusIntersect()

    Dim rng1 As Range, rng2 As Range, c As Range
    Dim rngInt As Range, rngUnion As Range
    Dim rngFinal As Range

    Set rng1 = Range("A1:B5,C6:D10")
    Set rng2 = Range("D9:G16")

    Set rngUnion = Application.Union(rng1, rng2)
    Set rngInt = Application.Intersect(rng1, rng2)

    If Not rngInt Is Nothing Then
        For Each c In rngUnion
            If Application.Intersect(c, rngInt) Is Nothing Then
                If rngFinal Is Nothing Then
                    Set rngFinal = c
                Else
                    Set rngFinal = Application.Union(rngFinal, c)
                End If
            End If
        Next c
    Else
        Set rngFinal = rngUnion
    End If

    rngFinal.Interior.Color = vbYellow

End Sub

答案 1 :(得分:1)

Union()方法(MSDN Reference)结合了整个范围,因此永远不会有r1r2中不属于Union(r1, r2)的部分。

但是,如果您正在寻找重叠(以及不重叠的单元格),您可以查看Intersect()方法(MSDN Reference)     Sub TestIt()

Dim r1 As Range, r2 As Range, r3 As Range
    Set r1 = Range("A1:D4")
    Set r2 = Range("C3:F6")
    Set r3 = Intersect(r1, r2)
    r1.Cells.Interior.Color = RGB(255, 0, 0)
    r2.Cells.Interior.Color = RGB(0, 255, 0)
    r3.Cells.Interior.Color = RGB(0, 0, 255)
    If r3 Is Nothing Then
        MsgBox "Ranges do not overlap"
    Else
        MsgBox "r1 and r2 overlap at " & r3.Address
    End If
End Sub

Intersect()方法的图片表示:

enter image description here

enter image description here

有一些与寻找非交叉部分有关的有趣功能。我建议@TimWilliam回答FOUND HERE

答案 2 :(得分:0)

如果x属于r1 => x属于r1和其他东西的联合。 没有属于r1的东西不属于联盟。 对于r2来说也一样。