Function RemoveIntersect(ByRef rng1 As Range, ByRef rng2 As Range, Optional bBothRanges As Boolean) As String
Dim wb As Workbook
Dim ws1 As Worksheet
Dim rng3 As Range
Dim lCalc As Long
'disable screenupdating, event code and warning messages.
'set calculation to Manual
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
lCalc = .Calculation
.Calculation = xlCalculationManual
End With
'add a working WorkBook
Set wb = Workbooks.Add(1)
Set ws1 = wb.Sheets(1)
On Error Resume Next
ws1.Range(rng1.Address).Formula = "=NA()"
ws1.Range(rng2.Address).Formula = vbNullString
Set rng3 = ws1.Cells.SpecialCells(xlCellTypeFormulas, 16)
If bBothRanges Then
ws1.UsedRange.Cells.ClearContents
ws1.Range(rng2.Address).Formula = "=NA()"
ws1.Range(rng1.Address).Formula = vbNullString
Set rng3 = Union(rng3, ws1.Cells.SpecialCells(xlCellTypeFormulas, 16))
End If
On Error GoTo 0
If Not rng3 Is Nothing Then RemoveIntersect = rng3.Address(0, 0)
'Close the working file
wb.Close False
'cleanup user interface and settings
'reset calculation
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
lCalc = .Calculation
End With
End Function
Sub Test_the_Code()
Dim rngTest1 As Range
Dim rngTest2 As Range
Dim rngWorking As Range
Dim strTemp As String
'Example 1
'Return the hidden cell range on the ActiveSheet
Set rngTest1 = ActiveSheet.UsedRange.Cells
Set rngTest2 = ActiveSheet.UsedRange.SpecialCells(xlVisible)
If rngTest1.Cells.Count > rngTest2.Cells.Count Then
strTemp = RemoveIntersect(rngTest1, rngTest2)
MsgBox "Hidden cell range is " & strTemp, vbInformation
Else
MsgBox "No hidden cells", vbInformation
End If
Set rngTest1 = Range("A1:A10,A5:D5")
Set rngTest2 = Range("A1:D1,D1:D10")
Set rngWorking = Intersect(rngTest1, rngTest2)
'Example 2
'Remove any range overlap from rngTest1
If Not rngWorking Is Nothing Then
strTemp = RemoveIntersect(rngTest1, rngTest2)
MsgBox "Cells removed = " & rngWorking.Address(0, 0) & vbNewLine & _
"Remaining range is " & strTemp, vbInformation
Else
MsgBox "No overlap"
End If
'Example 3
'Combine rngTest1 and rngTest2 where the ranges do not overlap
'Uses the Boolean True argument to combine the ranges
If Not rngWorking Is Nothing Then
strTemp = RemoveIntersect(rngTest1, rngTest2, True)
MsgBox "Cells removed = " & rngWorking.Address(0, 0) & vbNewLine & _
"New combined range is " & strTemp, vbInformation
Else
MsgBox "No cell overlap" & vbNewLine & _
"New combined range is " & Union(rngTest1, rngTest2).Address(0, 0), vbInformation
End If
End Sub