创build一些工作表并重命名它们

我创build了下面的代码来创build一些基于input的工作表并重命名它们。 打开文档时,会有两个名为“General”和“P-1”的页面,以“P-1”为模板。

我遇到的问题是,每当我启动macros并input一个数字,我会得到一个错误,告诉我名称已经分配。

Sub KlickME() Dim Rng As Range Dim WorkRng As Range Dim newName As String Dim convert As Integer Dim i As Integer Dim b As Integer newName = "P-" howMany = Application.InputBox("Many", "How Many", "", Type:=2) convert = CInt(howMany - 1) For i = 1 To convert Sheets("P-1").Copy After:=Sheets("P-1") For b = 1 To Application.Sheets.Count Application.Sheets(b).name = newName & b Next b Next i End Sub 

每当我运行没有“常规”工作表的macros而只有“P-1”工作表出现时,它的工作没有任何问题。

我把你的新代码缩短了一点:

 Sub KlickME() Dim howmany As Integer Dim i As Integer howmany = Application.InputBox("Many", "How Many", "", Type:=2) For i = 1 To howmany Sheets("P-1").Copy After:=Sheets(Sheets.Count) 'Inserts sheet on last position Sheets(Sheets.Count).Name = "P-" & i + 1 'renames sheet on last position Next i End Sub 

好吧,对于所有感兴趣的人,我解决了这个问题。 也许有点不合常规,但它做它应该做的。 请参阅下面的代码:

 Sub KlickME() Dim Rng As Range Dim WorkRng As Range Dim newName As String Dim convert As Integer Dim i As Integer Dim b As Integer newName = "P-" howMany = Application.InputBox("Many", "How Many", "", Type:=2) convert = CInt(howMany - 1) For i = 1 To convert Sheets("P-1").Copy After:=Sheets("P-1") Next i For b = 2 To Application.Sheets.Count Set Sheet = ActiveWorkbook.Worksheets(b) If Sheet.name <> "P-1" Then Application.Sheets(b).name = newName & b - 1 End If Next b End Sub