首页 > 解决方案 > 使用宏按钮根据模板和主工作表上的列表添加新选项卡

问题描述

我正在尝试创建一个宏按钮,该按钮根据 A 列中项目选项卡中的列表添加一个新选项卡。但是如果该选项卡已经存在,它不会创建一个并找到一个没有选项卡的任务。我正在使用这里已经提出的问题(宏从主选项卡中的列表在 Excel 中创建新选项卡,并在每个选项卡中填充具有相同名称的单元格)但我遇到了问题:

我使用了这段代码,但是当我在 . 我怎样才能得到这个来更新主表。我想要的是当一个项目被添加到主选项卡中的 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

有人可以帮忙吗?

谢谢!

标签: vbaexcel

解决方案


推荐阅读