首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果用户插入新工作表,则自动运行宏。

如果用户插入新工作表,则自动运行宏。
EN

Stack Overflow用户
提问于 2018-08-15 02:30:43
回答 1查看 74关注 0票数 0

如果我的宏检测到用户将一个新工作表插入到工作簿(现有的和新的)中,我希望它能够自动运行。

代码语言:javascript
复制
 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-15 02:52:38

正如注释中提到的,您需要在WorkbookNewSheet级别处理Application

代码语言:javascript
复制
'-- 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
代码语言:javascript
复制
'-- 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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51852154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档