我正在尝试根据我们在excel中使用VBA定期使用的模板动态生成自定义数量的工作表。
我创建了一个"概述"我们可以输入一个范围的页面,该范围将用于命名新工作表,但之后想要使用隐藏的" Master"工作表生成这些新工作表的内容。
我的下面的代码目前根据范围生成正确的页数并复制我们的主模板页面,但不将两者结合起来并将它们留在不同的页面中。
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
答案 0 :(得分:2)
所以我们只需要替换这一行:
Sheets.Add.Name = MyNewSheet.Value
这一行:
ActiveSheet.Name = MyNewSheet.Value
答案 1 :(得分:1)
如果工作表尚不存在,则循环浏览列表并复制工作表。
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