在excel vba中复制和重命名多个工作表

我使用下面的代码来复制一个主副本,每次我点击一个button。

当我把复制命令放在for循环中时,它会生成全部20个工作表。

不过,我想每一个button的点击产生一张表,并命名1,2 ..等等。

我把复制命令放在for循环之外

它完美地完成了第一页。 在下一次点击时,我得到一个错误400.任何协助生产这些工作表和重命名他们将n

Sub NewSheets() Dim i As Integer Dim ws As Worksheet Dim sh As Worksheet Set ws = Sheets("Template") Set sh = Sheets("Sheets Insert") Application.ScreenUpdating = 0 Sheets("Master").Copy After:=sh For i = 20 To 2 Step -1 'Sheets("Master").Copy After:=sh ActiveSheet.Name = i Next End Sub 

我想在每次点击一个button时生成一个表单,并命名为1,2 ..等等。

那么根本不要使用循环。 只需在button上单击一张新的工作表,并将工作表命名为正确的编号(1,2,3等)。 所以改变你的sub:

 Sub NewSheets() Dim i As Integer Dim ws As Worksheet Dim sh As Worksheet Set ws = Sheets("Template") ' Note that you are never using this... Set sh = Sheets(Sheets.Count) ' This will be the last sheet in the Workbook Application.ScreenUpdating = 0 Sheets("Master").Copy After:=sh ' change 3 to be the number of static sheets you have in the Workbook. Sheets(Sheets.Count).Name = Sheets.Count - 3 ' change 3 to the proper number End Sub 

我想我明白你需要做什么。 你的问题是因为你不能在没有声明全局variables的情况下循环。

为了得到我想要的工作 – 首先你需要声明一个全局variables – 就在模块的顶部:

 Global iter As Integer 

在这种情况下iter只是我的简写迭代 – 你可以任意调用它。

  Sub NewSheets() Dim i As Integer Dim ws As Worksheet Dim sh As Worksheet Set ws = Sheets("Template") Set sh = Sheets("Sheets Insert") Application.ScreenUpdating = 0 Sheets("Master").Copy After:=sh If iter = 0 Then iter = 1 End If ActiveSheet.Name = iter iter = iter + 1 If iter = 20 Then iter = 1 End If End Sub 

这使得您的代码更容易,因为您不需要物理循环。

这个变化从0到1有史以来 – 然后将计数添加新的表,直到它达到20(请记住这不会用于重新使用这些名称)