创建多个工作表并重命名它们

时间:2016-07-06 07:54:05

标签: excel vba excel-vba

我创建了以下代码,根据输入创建了许多工作表并重命名。打开文件时会有两个名为" General"和" P-1"其中" P-1"作为模板。

我遇到的问题是每当我启动宏并输入一个数字时,我都会收到错误,告诉我该名称已经分配。

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

每当我在没有" General"的情况下运行宏时工作表,只有" P-1"工作表存在,它没有任何问题。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

好的,对所有感兴趣的人,我解决了这个问题。也许有点不同寻常,但它确实做了它应该做的事情。请参阅以下代码:

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