I am using VBA code in a custom ribbon for Excel 2007 to insert a "helper" worksheet which is to be deleted after execution concludes.
However, under certain circumstances, execution stops after the "Worksheet.Add" function is called with no error, no debug text, and no pop-up message. I have added my own debug code after every line of code and nothing executes after the add function is called.
Code is below:
Private Function Difference(r1 As Range, r2 As Range) As Range
'Purpose: Returns a range containing only the cells which are not shared between the two passed ranges
Application.EnableEvents = False
On Error Resume Next
Dim s As String
Dim ws As Worksheet
Dim diff As Range, zRng As Range, cRng As Range
If Not r2 Is Nothing Then
On Error GoTo Sheet_Cleanup
If Not (r1.Parent Is r2.Parent) Then GoTo Exit_Code
Set ws = Worksheets.Add
For Each a In r1.Areas
Set zRng = chkUnion(zRng, ws.Range(a.Address))
Next a
zRng = 0
For Each b In r2.Areas
Set cRng = chkUnion(cRng, ws.Range(b.Address))
Next b
cRng.Clear
For Each c In ws.UsedRange.SpecialCells(xlCellTypeConstants).Areas
Set diff = chkUnion(diff, r1.Parent.Range(c.Address))
Next c
Sheet_Cleanup:
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
On Error Resume Next
Else
Set diff = r1
End If
If Not diff Is Nothing Then Set Difference = diff
Exit_Code:
Application.EnableEvents = True
End Function
This is not a desirable error state, as it leaves the worksheet in place, which must be deleted by the user.
What is more strange is that running the code again immediately after produces no such error event.
I have managed to reproduce the error on a specific worksheet, but it only occurs on the first instance of clicking the ribbon button and will not reoccur until the Excel session is closed and both the worksheet and ribbon add-in re-opened.