VBA code processing stops when adding or removing a named range

Viewed 71

I have an excel sheet where I am trying to create a named range dynamically in VBA. Maybe there's a better way to do it, but the existing way I am using should work based on multiple articles and tickets I have read on the topic. Using this method fails for me because the processing stop without an error when running this code. The range gets created or deleted on the line where processing stops, but of course I need processing to continue through the rest of the code. You should be able to replicate this issue in any excel sheet if you use this code snippet and run the test caller in testsub():

Option Explicit
Sub testsub()
Call SetDataRange("TestRange", ActiveWorkbook.Sheets("Sheet1"), 1, 2)
End Sub

Sub SetDataRange(RangeName As String, TargetSheet As Worksheet, LeftColumn As Integer, RightColumn As Integer)
On Error GoTo Fail

Dim WB As Workbook
Dim CRLastCell As Range
Dim rngDataRange As Range


Set WB = ActiveWorkbook
With TargetSheet
    Set CRLastCell = .Cells(.Rows.Count, "A").End(xlUp)
    Set rngDataRange = .Range(.Cells(1, LeftColumn), .Cells(CRLastCell.Row, RightColumn))
    On Error Resume Next
    Debug.Assert False ' Forcing a break for debug purposes.  The next line will cause the processing to stop without an error if the named range exists
    WB.Names.Item(RangeName & "_" & .Name).Delete
    Err.Clear
    On Error GoTo Fail
    Debug.Assert False ' Forcing a break for debug purposes.  The next line will cause the processing to stop without an error
    WB.Names.Add Name:=RangeName & "_" & .Name, RefersTo:="=" & .Name & "!" & rngDataRange.Address, Visible:=True
End With

Debug.Print RangeName & "_" & TargetSheet.Name & " " & ActiveWorkbook.Names.Item(RangeName & "_" & TargetSheet.Name).RefersTo
Exit Sub


   Fail:
        Debug.Print "Error: " & vbCrLf & Err.Number & vbCrLf & Err.Description
    End Sub

This is not my original code, but a recreation of the code I placed in a new workbook for simplest reproducible conditions.

Thanks

1 Answers

As suggested by EvR, I removed the code which was trying to delete the named range, thereby utilizing the feature in the names.add function that overwrites an existing name. This bypasses the issue without any undesired side effects, so I will consider this an answer to the question.

Related