Names can either have workbook scope of worksheet scope. Excel allows you to create multiple names with the same Name property if they have different scope.
So for example, I could have two names called "test" where one has workbook scope and one has worksheet scope. The problem is that if I have multiple names with the same name property and try to delete one of them, sometimes the wrong name is deleted.
Please see the example below to replicate the issue.
This appears to be a bug in the Excel object model. Does anyone know how to delete the correct name in this situation?
So for example, I could have two names called "test" where one has workbook scope and one has worksheet scope. The problem is that if I have multiple names with the same name property and try to delete one of them, sometimes the wrong name is deleted.
Please see the example below to replicate the issue.
This appears to be a bug in the Excel object model. Does anyone know how to delete the correct name in this situation?
VBA Code:
Sub NameDeletionWithScope()
Dim workbookName As Name, worksheetName As Name
Dim sWorkbookName As String, sWorksheetName As String, sRemainingName As String
'Delete all existing names for fresh demo
For i = ThisWorkbook.Names.Count To 1 Step -1
ThisWorkbook.Names(i).Delete
Next
Set workbookName = ThisWorkbook.Names.Add(Name:="test", RefersToR1C1:="=Sheet1!R1C1")
Set worksheetName = ThisWorkbook.Worksheets(1).Names.Add(Name:="test", RefersToR1C1:="=Sheet1!R1C1")
sWorkbookName = workbookName.Name ' workbook scope name "test"
sWorksheetName = worksheetName.Name ' worksheet scope name "Sheet1!test"
workbookName.Delete 'This should delete workbookName but instead deletes worksheetName
sRemainingName = ThisWorkbook.Names.Item(1).Name 'This should be "Sheet1!test" but is instead "test"
If sRemainingName = sWorkbookName Then
MsgBox "The name that was deleted had worksheet scope when it should have workbook scope"
End If
End Sub