从另一个工作簿管理和导入命名范围

Managing and importing named ranges from another workbook

我正在查看此处提供的代码 (),但显然我可以使用一些指导。

Public Sub RescopeNamedRangesToWorkbookV2()
Dim wb As Workbook
Dim ws As Worksheet
Dim objNameWs As Name
Dim objNameWb As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name

'Loop through names in worksheet.
For Each objNameWs In ws.Names


'Check name is visble.
    If objNameWs.Visible = True Then
'Check name refers to a range on the active sheet.
        If InStr(1, objNameWs.RefersTo, sWsName, vbTextCompare) Then
            sRefersTo = objNameWs.RefersTo
            sObjName = objNameWs.Name
'Check name is scoped to the worksheet.
            If objNameWs.Parent.Name <> sWbName Then
'Delete the current name scoped to worksheet replacing with workbook scoped name.
                sObjName = Mid(sObjName, InStr(1, sObjName, "!") + 1, Len(sObjName))
'Check to see if there already is a Named Range with the same Name with the full workbook scope.
                For Each objNameWb In wb.Names
                    If sObjName = objNameWb.Name Then
                    MsgBox "There is already a Named range with ""Workbook scope"" named """ + sObjName + """. Change either Named Range names or delete one before running this Macro."
                    Exit Sub
                    End If
                Next objNameWb
                objNameWs.Delete
                wb.Names.Add Name:=sObjName, RefersTo:=sRefersTo
            End If
        End If
    End If
Next objNameWs
End Sub

我的设置,2 excel 个文件,WB1 和 WB2,其中 WB1 是活动文件。 WB1 和 WB2 都有命名范围。所有名称都在其自己的 WB 中定义为全局名称。 两个 WB 都有特定 WB 独有的名称,但也有通用名称,即。指国家

我尝试实现的最终目标是能够将特定工作表从 WB2 导入 WB1,其中:

我问的原因是因为我有很多具体的计算表,每一个都针对某个主题。 它们中的每一个都可以用作独立文件。 但是当我必须为一个项目计算多个主题时,我希望从 WB2 导入特定的计算表并将这些表链接到或使用 WB1 中已有的基本数据(例如客户、国家/地区、特定费率、交货时间、 ……) 目前所有计算表都在一个 WB 中,但这变得非常慢

看来我做起来有点困难

正在替换:

MsgBox "There is already a Named range with ""Workbook scope"" named """ + sObjName + """. Change either Named Range names or delete one before running this Macro."
Exit Sub

sRefersTo = objNameWb.RefersTo

似乎可以解决问题

此外,就像我的情况一样,您可能想要查找外部引用范围并删除它们,因为它们会创建双重名称(名称相同但链接到当前文件和外部文件并且都是全局范围的)