从工作表中的列创建工作表并使用另一个工作表作为模板

时间:2017-09-01 14:07:04

标签: excel excel-vba excel-formula vba

这是代码:

Sub CreateSheetsFromAList()
    Dim MyCell As Range, MyRange As Range

    Set MyRange = Sheets("Company").Range("B2")
    Set MyRange = Range(MyRange, MyRange.End(xlDown))

    For Each MyCell In MyRange
        Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
        Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet   
    Next MyCell
End Sub

这会根据我的列创建新的工作表现在我有一个我需要用作“模板”的第二部分,即它有标题信息和按钮。

Sub Wsh_PasteSpecial()
Dim WshSrc As Worksheet
Dim WshTrg As Worksheet

Rem Set working worksheets
Set WshSrc = ThisWorkbook.Worksheets("RecordsTemplate") '<-- my template

Set WshTrg = ThisWorkbook.Worksheets("Target") '<-- QUESTION IS HOW DO I SET THE TARGET.

    WshSrc.Cells.Copy
    With WshTrg.Cells
        .PasteSpecial Paste:=xlPasteColumnWidths
        .PasteSpecial Paste:=xlPasteFormats
        .PasteSpecial Paste:=xlPasteFormulasAndNumberFormats
        Application.CutCopyMode = False
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

我合并了你的两个代码:

Sub CreateSheetsFromAList()
    Dim MyCell As Range, MyRange As Range
    Dim WshSrc As Worksheet
    Dim WshTrg As Worksheet

    Set MyRange = Sheets("Company").Range("B2")
    Set MyRange = Range(MyRange, MyRange.End(xlDown))
    Set WshSrc = ThisWorkbook.Worksheets("RecordsTemplate") '<-- my template

    For Each MyCell In MyRange
        Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
        Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet   
        Set WshTrg = ThisWorkbook.Worksheets(MyCell.Value)  
        WshSrc.Cells.Copy
        With WshTrg.Cells
            .PasteSpecial Paste:=xlPasteColumnWidths
            .PasteSpecial Paste:=xlPasteFormats
            .PasteSpecial Paste:=xlPasteFormulasAndNumberFormats
            Application.CutCopyMode = False
        End With      
    Next MyCell
End Sub