简体   繁体   English

Excel:在新应用程序中打开工作簿不会运行Workbook_Open事件

[英]Excel: Open Workbook in a new application does not run the Workbook_Open event

From the code of Excel A , I want to open Excel B. 我想从Excel A的代码中打开ExcelB。

Using this code, the new Excel is open in a new Excel Application, so you have 2 independent Excel windows, BUT! 使用此代码,将在新的Excel应用程序中打开新的Excel,因此您有2个独立的Excel窗口,但是! The Workbook_Open code of the sFileB is not executed: sFileB的Workbook_Open代码未执行:

Dim myApp As New Excel.Application
myApp.Workbooks.Open sFileB
myApp.Visible = True

If I open the new Excel inside the same application then I have only 1 Excel windows with the 2 files open, but opening the file in this way the Workbook_Open event is executed correctly: 如果我在同一应用程序中打开新的Excel,则只有1个Excel窗口打开了2个文件,但是以这种方式打开文件时,可以正确执行Workbook_Open事件:

Workbooks.Open sFileB

I want to open the new excel sFileB in a new application and, of course, I want to execute the Workbook_Open code of sFileB. 我想在新的应用程序中打开新的excel sFileB,当然,我想执行sFileB的Workbook_Open代码。 Do you know the reason of why in the first case the Workbook_Open is not executed? 您是否知道为什么在第一种情况下不执行Workbook_Open的原因? Any solution to force the execution of the event? 有什么办法可以强制执行事件? Maybe I'm doing something wrong... Thanks for your help! 也许我做错了...感谢您的帮助!

Use this 用这个


Option Explicit

Public Sub OpenXLFileInNewInstance()

    Dim xlApp As Excel.Application, wb As Workbook

    Set xlApp = CreateObject("Excel.Application")

    xlApp.Visible = True

    Set wb = xlApp.Workbooks.Open("D:\Tmp\xTemplate.xlsm")

    'wb.Close False
    'xlApp.Quit

End Sub

Thanks to Paul's answer, I could do some more testing and discovered that the point is to write FIRST the line myApp.Visible = True before the line myApp.Workbooks.Open sFileB . 感谢Paul的回答,我可以做更多的测试,发现关键是要先在myApp.Workbooks.Open sFileB行之前编写myApp.Visible = True行。

So this is the definitive working code: 因此,这是确定的工作代码:

Set myApp = CreateObject("Excel.Application")
myApp.Visible = True
myApp.Workbooks.Open sFileB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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