2

I have an excel sheet with defined names I would like to copy it with VBA by copying also the defined names. How can I do?

My current macro to copy the sheet:

Sub myMacro()
Const BASE_NAME As String = "MySheet"
Dim sheet_name As String
Dim i As Integer
Dim num_text As String
Dim new_num As Integer
Dim max_num As Integer
Dim new_sheet As Worksheet

' Find the largest number in a sheet name after the
' base name.
max_num = 0
For i = 1 To Sheets.Count
    sheet_name = Sheets(i).Name
    If Left$(sheet_name, Len(BASE_NAME)) = BASE_NAME _
        Then
        num_text = Mid$(sheet_name, Len(BASE_NAME) + 1)
        new_num = Val(num_text)
        If new_num > max_num Then max_num = new_num
    End If
Next i

' Make a new sheet with a new number.
Set new_sheet = Sheets.Add(after:=Sheets(Sheets.Count))
new_sheet.Name = BASE_NAME & Format$(max_num + 1)
new_sheet.Select
Sheets("MySheet_template").Range("A1:DQ1109").Copy 

Destination:=Sheets(new_sheet.Name).Range("A1")
End Sub
Thegamer23
  • 537
  • 1
  • 8
  • 20
  • Take a look at [this answer](http://stackoverflow.com/a/35873183/4717755) and [this answer](http://stackoverflow.com/a/31956023/4717755) to see if that helps. – PeterT May 19 '17 at 13:46
  • Actually I could not solve. I cannot manage to copy the sheet and keep its defined names. – Thegamer23 May 28 '17 at 17:55

1 Answers1

0

Try this - a slightly different approach

Sub myMacro()
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Dim sh As Shape, strtSh As Worksheet
    Set strtSh = ActiveSheet
    Sheets("MySheet_template").Copy after:=Sheets(Sheets.Count)
    ActiveSheet.Name = "MySheet" & Sheets.Count - 1
    For Each sh In ActiveSheet.Shapes
        sh.Delete
    Next sh
    strtSh.Select
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub
curious
  • 1,504
  • 5
  • 18
  • 32