如何重复和重命名包含数字的选项卡

时间:2019-01-16 23:04:48

标签: excel vba

我正在尝试创建一个代码,该代码将复制并重命名名为“ 001”的模板标签。问题是,我希望每个重复的选项卡都被命名为“ 001 +1”。因此,重复的标签页的名称应为“ 002,003,...,010,011 ... 100,101等”。

重复的数量将由在出现的消息框中输入的数量决定,询问“您要制作多少份?”。另外,如果以后要添加更多的选项卡副本,我也希望没有重复项或名为“ 001(2)”的选项卡。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这里是一种方法:

Sub Tester()
    CreateSheets 4
End Sub


'EDIT: added specific workbook reference to qualify sheet references
Sub CreateSheets(howMany As Long)
    Dim nm As String, sht As Worksheet
    Dim i As Long, n As Long, wb As Workbook

    Set wb = ThisWorkbook
    For n = 1 To howMany
        i = 2
        Do
            nm = Format(i, "000")
            Set sht = Nothing
            'see if this sheet exists...
            On Error Resume Next
            Set sht = wb.Sheets(nm)
            On Error GoTo 0
            If sht Is Nothing Then
                'get the sheet to copy the template after
                Set sht = wb.Sheets(Format(i - 1, "000"))
                wb.Sheets("001").Copy after:=sht
                wb.Sheets(sht.Index + 1).Name = nm
                Exit Do 'made our copy
            End If
            i = i + 1
        Loop
    Next n
End Sub