首页 > 解决方案 > 如何以增量方式复制和重命名包含数字的选项卡

问题描述

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

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

我真的很感谢你的帮助。

标签: excelvba

解决方案


这是一种方法:

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

推荐阅读