Home » excel » excel – VBA Clear cell names in range

excel – VBA Clear cell names in range

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to clear the names of all named cells within a range before executing a procedure.

I’ve tried the following code with no success so far:

Sub EraseCellNames()

Worksheets("SheetA").Range("A1:G5").Select
Dim nName As Name
    For Each nName In Names
        If Not Intersect(Selection, Range(nName.Name)) Is Nothing Then
            nName.Delete
        End If
    Next nName

End Sub

Any ideas?

Thanks in advance!

enter image description here

How to&Answers:

Try this one:

Sub EraseCellNames()
    Dim nName As Name
    Dim targetRng As Range

    Set targetRng = Worksheets("SheetA").Range("A1:G5")

    For Each nName In ThisWorkbook.Names
        If nName.ValidWorkbookParameter Then
            If targetRng.Parent.Name = nName.RefersToRange.Parent.Name Then
                If Not Intersect(targetRng, nName.RefersToRange) Is Nothing Then nName.Delete
            End If
        End If
    Next nName
End Sub