I have hacked together code (from a couple of sources, references at the bottom) that programmatically will take worksheet scoped named ranges and convert them to workbook named ranges. However my code only works for some named ranges and not others, and I can't figure out why.
The reason I'm having to do this is because I had to delete two tabs (one of the tabs containing _T and the other _X) from the original source and copy in the duplicates of these tabs from another source. This leaves me with workbook scoped named ranges of #REF!#REF and worksheet named ranges that have the ranges I want but I need them Workbook scoped.
See code below
If I run this code looking for "_T", it works perfectly. All workbook named ranges starting with _T that were #REF!#REF now have the correct range and their counterpart worksheet named ranges are deleted. HOWEVER, if I run this looking for "_X", the workbook named range goes unchanged. I'm stumped. I have even tried a different approach where I manually delete all of the current workbook named ranges starting with _X, and then programmatically try to Add them using ActiveWorkbook.Names.Add Name:=newNm,RefersTo:=nm.RefersTo
which also does nothing (doesn't even add a new record).
Thanks in advance for the help.
Sub WStoWBscope()
Dim nm As Name, Ans As Integer, newNm As String, fltr As String
fltr = "_X" 'search string
For Each nm In ActiveWorkbook.Names 'look at all named ranges within the current workbook
If nm.Name Like "X!*" Then 'looks for worksheet scoped named range that has the correct range
If InStr(1, nm.Name, fltr) > 0 Then
newNm = Replace(nm.Name, "X!", "") 'save name of existing workbook named range
Range(nm.RefersTo).Name = newNm 'overwrite workbook named range with proper range
nm.Delete 'deletes worksheet named range
End If
End If
Next nm
End Sub
VBA to Convert Named Ranges Workbook to Worksheet Scope VBA to change the scope of named ranges from worksheet level to workbook
Try this:
Sub ConvertWorksheetNamedRangesToWorkbookNamedRanges()
Dim nName As Name
'Loop Through each named Range
For Each nName In ActiveWorkbook.Names
'Is Name scoped at the Workbook level?
If TypeOf nName.Parent Is Workbook Then
End If
'Is Name scoped at the Worksheet level?
If TypeOf nName.Parent Is Worksheet Then
' If nm.Name Like "X!*" Then .....
' Do the filtering you need
' ....
Dim sName As String
sName = nName.Name 'Save the name of the name
Dim rngName As Range
Set rngName = Range(nName) ' Save the range of the name
nName.delete ' Delete the name
'Create a new one on workbook scope
ThisWorkbook.Names.Add Name:=sName, RefersToR1C1:="=" & rngName.Address(ReferenceStyle:=xlR1C1)
' End If
End If
Next nName
End Sub