自动重命名多个工作表并将main的内容复制到所有新创建的工作表

时间:2015-11-18 19:18:18

标签: excel vba copy-paste

我有一张包含格式化列的主表(B2:Y14和A18:B24),我正在尝试创建与即将到来的月份一样多的工作表,然后将主工作表数据复制到每个新创建的工作表中

例如:对于12月份,我需要创建31张名为DEC1 ... DEC31的表格,其中包含主表格中的数据。

我尝试的是以下内容:

Sub AddSheets()
    Dim j As Integer
    Dim curSheet As String
    Dim prevSheet As String

    'Dim summarySheet As Workbook

    newName = Application.InputBox("Name", "Rename Sheet", "", Type:=2)
    numSheets = Application.InputBox("Range", "Number of Sheets", "", Type:=1)

    prevSheet = "Main"
    'Set summarySheet = Sheets("Main").UsedRange.Copy


    For j = 1 To numSheets
        Sheets.Add After:=Sheets(CStr(prevSheet))
        curSheet = newName & " " & j
        Sheets(CStr(curSheet)).Name = curSheet
        Sheets("Main").UsedRange.Copy
        Sheets(CStr(curSheet)).Select
        Sheets(CStr(curSheet)).Paste
        prevSheet = curSheet
        'ActiveSheet.Paste
    Next j
End Sub

1 个答案:

答案 0 :(得分:0)

最简单的方法是在添加时将新工作表设置为变量。然后你可以参考它。

Sub AddSheets()
    Dim j As Integer
    Dim prevSheet As String
    Dim newsht As Worksheet
    'Dim summarySheet As Workbook

    newName = Application.InputBox("Name", "Rename Sheet", "", Type:=2)
    numSheets = Application.InputBox("Range", "Number of Sheets", "", Type:=1)

    prevSheet = "Main"
    'Set summarySheet = Sheets("Main").UsedRange.Copy


    For j = 1 To numSheets
        Set newsht = Sheets.Add(After:=Sheets(CStr(prevSheet)))
        newsht.Name = newName & " " & j
        Sheets("Main").UsedRange.Copy newsht.Range("A1")
        prevSheet = newsht.Name

    Next j
End Sub