使用宏按钮基于模板和主表上的列表添加新选项卡

时间:2018-07-05 08:13:44

标签: excel vba excel-vba

我试图创建一个宏按钮,该宏按钮基于A列的项目标签中的列表添加一个新标签。但是如果该标签已经存在,则不会创建一个新标签,并且会找到一个没有标签的任务。我使用的是这里已经问过的问题(Macro to create new tabs in Excel from a list in a Master tab and populate a cell in each tab with the same name),但遇到了问题:

我使用了这段代码,但是当我在的A列中将新项目添加到列表中时,始终遇到运行时错误1004。我该如何更新母版表。我想要的是将一个项目添加到“主”选项卡的A列中时,我可以单击按钮并进行更新。

当所有项目都列在A列中,然后我按下按钮时,代码便起作用了,但是一旦我添加新项目,我就会收到错误消息?

我对代码进行了一些更新,以适应我的需要,但其内容如下:

Sub Add_Projet_Button()
    Dim masterSheet As Worksheet
    Dim hiddenSheet As Worksheet
    Dim NewSheet As Worksheet
    Dim myBook As Workbook
    Dim lastRow As Long
    Dim i As Long
    Dim namesColumn

    'Define your workbook - here set as the active workbook, assuming it contains 
    masterSheet and hiddenSheet
    Set myBook = ActiveWorkbook

    'Define your worksheets - The sheets are named "Master" and "Hidden" 
    respectively
    Set masterSheet = myBook.Worksheets("Projects")
    Set hiddenSheet = myBook.Worksheets("TEMPLATE")

    'Define which column in your master tab the list is - here it's A i.e. column 1
    namesColumn = 1

    'Find the last row of the sheets list
    lastRow = masterSheet.Cells(masterSheet.Rows.Count, namesColumn).End(xlUp).Row

    'Cycle through the list - Assuming the list starts in column "A" from the 2nd row
    For i = 3 To lastRow
        With myBook
            'New sheet
            Set NewSheet = .Worksheets.Add(After:=.Worksheets("Projects"))
        End With

        'Find name of the tab and naming the tab
        tabName = masterSheet.Cells(i, namesColumn)
        NewSheet.Name = tabName

        'Copy from hidden template - You can choose the ranges if predefined or use .Cells(r,c) to do something fancier
        hiddenSheet.Range("A1:BF950").Copy _
          Destination:=NewSheet.Range("A1:BF950")

        'Paste in e.g. cell A1 i.e. (1,1) the tab name
        NewSheet.Cells(2, 1).Value = tabName
    Next i
End Sub

有人可以帮忙吗?

谢谢!

0 个答案:

没有答案