BigBeachBananas
Active Member
- Joined
- Jul 13, 2021
- Messages
- 450
- Office Version
- 365
- Platform
- Windows
- MacOS
For context, I currently have a VBA that copies a sheet from sourceWB to destWB. My issue is that when you copy a sheet, the named ranges get copied over to the destWB as well. I'm looking for a VBA code that deletes any named ranges that refer to the sourceWB. I'm thinking of looking for any named ranges under RefersTo that start with a single quote and deleting it, however, my code doesn't look like it's doing it.
VBA Code:
Sub DeleteNamedRangesReferringToOtherWorkbooks()
Dim wb As Workbook
Dim nm As Name
Dim deleteList As New Collection
Dim nameToDelete As String
' Loop through all open workbooks
For Each wb In Workbooks
' Loop through all named ranges in the current workbook
For Each nm In wb.Names
nameToDelete = nm.Name
' Check if the named range refers to another workbook
If Left(nameToDelete, 1) = "'" Then
' Add the named range to the delete list
deleteList.Add nameToDelete
End If
Next nm
Next wb
' Delete the named ranges in the delete list
For Each nameToDelete In deleteList
On Error Resume Next ' Ignore errors if the named range doesn't exist
ThisWorkbook.Names(nameToDelete).Delete
On Error GoTo 0 ' Reset error handling
Next nameToDelete
End Sub