Im looking for Excel VBA code to automatically duplicate Tab 1 in workbook when a table in Tab 2 is populated with a name

喜你入骨 提交于 2021-01-29 09:02:40

问题


VBA code needed:

I have 2 tabs in a workbook. Tab 1 (DIST "A") is a formatted spreadsheet & Tab 2 (RFP) has a table with a column called "Distributor". When I enter names under the Distributor list, could be 1 or 30 differnet names, I want VBA to automatically duplicate Tab 1, rename the duplicated sheet to whatever name I entered, and send it to end of workbook.

Here's my current code, its duplicating the ACTIVE SHEET, Tab 2 and not Tab 1 (what I need)

Sub Copyrenameworksheet()

Dim ws As Worksheet
Set wh = Worksheets(ActiveSheet.Name)
ActiveSheet.Copy After:=Worksheets(Sheets.Count)
If wh.Range("A1").Value <> "" Then
ActiveSheet.Name = wh.Range("A1").Value
End If
wh.Activate
End Sub

回答1:


Apart from very the nice documentation provided by BigBen, you may look at Worksheet Change Event tutorial.

It should be a bit easier to understand with this step-by-step introduction.


Basically what should be done could be the following:

  1. Using 'Intersection' method from the code in the tutorial/documentation check whether your list has been changed.
  2. Check whether the added worksheet already exists [optional]
  3. Duplicate the worksheet and set its name to Target.Value

Put the following code into sheet object for 'RFP' worksheet (see the tutorial I linked). Substitute "A1:A3" range with the range of your distributor list. When you enter new distributor, a message box with the name of the distributor should pop up.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:A3")) Is Nothing Then
        Application.EnableEvents = False


            MsgBox (Target.Value)


        Application.EnableEvents = True
    End If
End Sub

Now write code that duplicates the worksheet and changes its name to Target.Value and basically all you need to do is to put it instead of MsgBox.



来源:https://stackoverflow.com/questions/60062957/im-looking-for-excel-vba-code-to-automatically-duplicate-tab-1-in-workbook-when

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!