如果宏检测到用户插入了新的工作表,则会自动运行

时间:2018-08-15 02:30:44

标签: excel vba excel-vba

如果希望宏检测到用户在工作簿中插入了一个新的工作表(现有的和新的),我希望它自动运行。谁能帮我改善我的代码,因为我周围找不到类似的想法?

 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

1 个答案:

答案 0 :(得分:1)

如评论中所述,您需要在WorkbookNewSheet级处理Application


'-- 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