VBA 运行 另一个 excel 实例中的代码并分离

VBA run code in another instance of excel and detach

我目前有以下代码在 excel 的新实例中打开工作簿(打开的工作簿有一个 on open 宏)。

然而,当新实例中的代码为 运行 时,这也会占用 excel 的现有实例,并且只有在工作簿打开宏具有 run.Is 时才会释放它如何在新实例中打开 excel 并立即 detach/stop 现有工作簿中的代码?

请看下面的代码。

Sub OpenWBInNewInstance()
    Dim xApp As Excel.Application
    Set xApp = New Excel.Application
    xApp.Visible = True

    Dim wb As Excel.Workbook
    Set wb = xApp.Workbooks.Open("Z:\MI\Not Purchased Detail\Not Purchased Detail Disposal Marketing Template.xlsb")
End Sub

代码执行在 VBA 中的单个线程上运行,因此您无法执行您要求的操作,因为执行不会移动到下一行,直到整个 Workbooks.Open 行已处理 - 其中包括另一个工作簿中的 Workbook_Open 事件。

使用 VBScript 代替的可能解决方法:

    Sub OpenWBInNewInstance()

    Open Environ$("USERPROFILE") & "\Desktop\temp.vbs" For Output As #1
        Print #1, "Set xl = CreateObject(""Excel.Application"")"
        Print #1, "xl.Workbooks.Open ""Z:\MI\Not Purchased Detail\Not Purchased Detail Disposal Marketing Template.xlsb"""
    Close #1

    Shell Environ$("USERPROFILE") & "\Desktop\temp.vbs"

    '// You will need some kind of hook here to set the workbook in other instance...