简体   繁体   中英

Automatically run macro if the user inserted a new worksheet

I would like my macro to run automatically if it detects that the user inserted a new worksheet into the workbook (existing & new).

 Sub macro_run()

    Dim Newws As Worksheet
    Dim wb As Excel.Workbook
    Dim sample1 As Worksheet

    With ThisWorkbook
        Set sample1 = .Sheets("Template")

        For Each wb In Application.Workbooks
            If Newws = sample1 Then
                Application.Run "PERSONAL.XLSB!Opennew"
            End If
        Next wb
    End With

End Sub

As mentioned in the comments you need to handle WorkbookNewSheet at Application level.


'-- Create a new Class.
'-- Name it clsGlobalHandler.
'-- Following Code goes in that class

'/ Create a variable to hold Application Object
Public WithEvents xlApp As Application

'/ Handle NewSheet event. Invoked whenever a new sheet is added
Private Sub xlApp_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
    MsgBox Sh.Name
End Sub

'-- Create a new module
'-- Following code goes there

Option Explicit

'/ A new instance  for the Class that we created.
Dim oGh As New clsGlobalHandler

'/ To start tracking sheet additions call this method first. Most likely in WorkBook_Open
'/ Once called any new sheet across the app insatnce will be intercepted.
Sub SetGlobalHandler()
    Set oGh.xlApp = Application
End Sub

'/ Call this to remove the global handler.
Sub ResetGlobalHandler()
    Set oGh.xlApp = Nothing
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM