2016-01-06 124 views
1

我想根據我們在Excel中使用VBA定期使用的模板動態生成自定義數量的工作表。多次動態複製工作表並在Excel中使用VBA重命名

我已經創建了一個「概述」頁面,我們可以在其中輸入一個用於命名新工作表的範圍,但隨後想使用隱藏的「主」工作表來生成這些新工作表的內容。

我下面的代碼根據範圍生成正確數量的頁面並複製我們的主模板頁面,但不會將兩者合併,並將它們留在單獨的頁面中。

Sub test() 
Dim MyNames As Range, MyNewSheet As Range 

Set masterSheet = ThisWorkbook.Worksheets("Master") 
Set MyNames = Range("A1:A6").CurrentRegion ' load range into variable 

For Each MyNewSheet In MyNames.Cells ' loop through cell range 
    masterSheet.Copy ThisWorkbook.Sheets(Sheets.Count) 'copy master template sheet 
    Sheets.Add.Name = MyNewSheet.Value 
Next MyNewSheet 

MyNames.Worksheet.Select ' move selection to original sheet 
End Sub 

正如你看到的,代碼生成兩個命名(空白)工作表,並複製我的主人的工作表,默認爲命名爲「主()」。 enter image description here

+2

我覺得你只是NEET與此'ActiveSheet.name = MyNewSheet.Value' – Fadi

+0

不知道,但昏暗的WS作爲excel.worksheet替換該行'Sheets.Add.Name = MyNewSheet.Value':集ws = masterSheet.Copy ThisWorkbook.Sheets(Sheets.Count):ws.name = mynewsheet.value –

+0

@DanBeard,不客氣,我張貼這個答案 – Fadi

回答

2

所以我們只需要更換這行:通過列表

ActiveSheet.Name = MyNewSheet.Value 
1

循環,如果表不存在複製的工作表:與此訂單

Sheets.Add.Name = MyNewSheet.Value 

Sub CopyMaster() 
    Dim ws As Worksheet, sh As Worksheet 
    Dim Rws As Long, rng As Range, c As Range 
    Set sh = Sheets("Overview") 
    Set ws = Sheets("Master") 

    With sh 
     Rws = .Cells(Rows.Count, "A").End(xlUp).Row 
     Set rng = .Range(.Cells(1, 1), .Cells(Rws, 1)) 
    End With 
    For Each c In rng.Cells 
     If WorksheetExists(c.Value) Then 
      MsgBox "Sheet " & c & " exists" 
     Else: 
      ws.Copy After:=Worksheets(Worksheets.Count) 
      Worksheets(Worksheets.Count).Name = c.Value 

     End If 
    Next c 
End Sub 
Function WorksheetExists(WSName As String) As Boolean 
    On Error Resume Next 
    WorksheetExists = Worksheets(WSName).Name = WSName 
    On Error GoTo 0 
End Function 
相關問題