【问题标题】:VBA run code in another instance of excel and detachVBA 在另一个 excel 实例中运行代码并分离
【发布时间】:2016-06-03 08:24:35
【问题描述】:

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

但是,当代码在新实例中运行时,这也会占用现有的 excel 实例,并且只有在工作簿打开宏运行后才会释放它。有没有办法在新实例中打开 excel 并分离/停止立即从现有工作簿中获取代码?

请看下面的代码。

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 不能在多个线程上运行,因此只有在完成整个“打开”事件后才会将执行返回到此代码。我知道解决这个问题的唯一方法是将命令输出到 VBS 文件和 shell,而不是
  • 想要举办公开赛吗?如果没有,请在打开工作簿之前禁用事件?

标签: vba excel instance


【解决方案1】:

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

一种可能的解决方法是使用 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...

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2021-02-01
    • 1970-01-01
    • 2017-04-22
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多