Here are some range set algebra functions you can play with.
' ======================================
' Set Algebra Functions for Ranges
' shg 2007-0720
' Rev 2008-1010
' ======================================
Function RangeXOr(rngA As Range, rngB As Range) As Range
' Returns Symmetric Difference of rngA and RngB
' RangeXOR = Union(rngA, rngB) - Intersect(rngA, RngB)
Dim cell As Range
If rngA Is Nothing Then
Set RangeXOr = rngB
ElseIf rngB Is Nothing Then
Set RangeXOr = rngA
Else
For Each cell In Union(rngA, rngB)
If Intersect(cell, rngA, rngB) Is Nothing Then
If RangeXOr Is Nothing Then
Set RangeXOr = cell
Else
Set RangeXOr = Union(RangeXOr, cell)
End If
End If
Next
End If
End Function
Function RangeComp(rngA As Range, rngB As Range) As Range
' Returns the Relative Complement of rngA in rngB
' RangeComp = rngB - RngA
Dim cell As Range
If rngA Is Nothing Then
Set RangeComp = rngB
ElseIf rngB Is Nothing Then
' nothing to do; will return Nothing
Else
For Each cell In rngB
If Intersect(cell, rngA) Is Nothing Then
If RangeComp Is Nothing Then
Set RangeComp = cell
Else
Set RangeComp = Union(RangeComp, cell)
End If
End If
Next
End If
End Function
Function RangeBox(rng As Range) As Range
' Returns a single range bounding the cells in rng
Dim iRowBeg As Long, iRowEnd As Long
Dim iColBeg As Long, iColEnd As Long
Dim iRow As Long, iCol As Long
Dim nRow As Long, nCol As Long
Dim rArea As Range
Dim wksDad As Worksheet
Set wksDad = rng.Parent
iRowBeg = wksDad.Columns.Count
iColBeg = wksDad.Rows.Count
If rng.Areas.Count = 1 Then
Set RangeBox = rng
Else
For Each rArea In rng.Areas
iRow = rArea.Row
iCol = rArea.Column
nRow = rArea.Rows.Count
nCol = rArea.Columns.Count
iRowBeg = IIf(iRow < iRowBeg, iRow, iRowBeg)
iColBeg = IIf(iCol < iColBeg, iCol, iColBeg)
iRowEnd = IIf(iRow + nRow - 1 > iRowEnd, iRow + nRow - 1, iRowEnd)
iColEnd = IIf(iCol + nCol - 1 > iColEnd, iCol + nCol - 1, iColEnd)
Next rArea
With wksDad
Set RangeBox = Range(.Cells(iRowBeg, iColBeg), .Cells(iRowEnd, iColEnd))
End With
End If
End Function
Function IsSameRange(r1 As Range, r2 As Range) As Boolean
Dim rArea As Range
For Each rArea In Union(r1, r2).Areas
If Intersect(rArea, r1).Address <> rArea.Address Then Exit Function '-->
If Intersect(rArea, r2).Address <> rArea.Address Then Exit Function '-->
Next
IsSameRange = True
End Function
Select some odd collection of cells, and from the VBE Immediate window, try
RangeBox(selection).Select
RangeComp(selection, RangeBox(selection)).Select
Bookmarks