复制表而不创建命名范围的新实例?

时间:2016-01-27 21:32:52

标签: excel vba excel-vba

我使用以下代码复制工作表。我还有一些命名范围作为工作簿的范围。问题是,当我执行复制时,它会创建具有新工作表范围的所有命名范围的副本。一切都当然有效,但我可能有20多张。我不需要80个命名范围,大多数是重复的。我怎么能避免这个?

Sub btnCopyTemplate()
    Dim template As Worksheet
    Dim newSheet As Worksheet
    Set template = ActiveWorkbook.Sheets("Template")
    template.Copy After:=Sheets(Sheets.Count)
    Set newSheet = ActiveSheet
    newSheet.Name = "NewCopy"
End Sub

副本名称管理员:

enter image description here

1 个答案:

答案 0 :(得分:7)

以下是我的回答:

Sub btnCopyTemplate()
    Dim template As Worksheet
    Dim newSheet As Worksheet
    Set template = ActiveWorkbook.Sheets("Template")
    template.Copy After:=Sheets(Sheets.Count)
    Set newSheet = ActiveSheet
    newSheet.Name = "NewCopy"
    deleteNames 'Check the sub
End Sub

Sub deleteNames()
    Dim theName As Name
    For Each theName In Names
        If TypeOf theName.Parent Is Worksheet Then
            theName.Delete
        End If
    Next
End Sub

这样你就可以删除范围"工作表"的所有名称。并保留"工作簿"名称

修改#2

在阅读之后,这里的评论是更新传递工作表只循环" newSheet"

Sub btnCopyTemplate()
    Dim template As Worksheet
    Dim newSheet As Worksheet
    Set template = ActiveWorkbook.Sheets("Template")
    template.Copy After:=Sheets(Sheets.Count)
    Set newSheet = ActiveSheet
    newSheet.Name = "NewCopy"
    deleteNames newSheet
End Sub

Sub deleteNames(sht As Worksheet)
    Dim theName As Name
    For Each theName In Names
        If (TypeOf theName.Parent Is Worksheet) And (sht.Name = theName.Parent.Name) Then
            theName.Delete
        End If
    Next
End Sub