简体   繁体   English

从Excel中的Interop(C#)应用程序运行的Excel宏在完成执行之前返回

[英]Excel macro run from Interop (C#) application in Excel returns before it completes it's execution

My macro sub ('first-sub') ends by calling another sub ('second-sub') from Application.OnTime, with a wait time of 5 seconds. 我的宏子(“第一子”)通过从Application.OnTime调用另一个子(“第二子”)结束,等待时间为5秒。 My C# application however gets back the control after the 'first-sub' execution is done. 但是,我的C#应用​​程序在执行“第一子”操作后取回了控件。 It doesn't wait for the 'second-sub' to be completed. 它不等待“第二个子”完成。 Is there a way, my C# application can wait till both the macros complete their run? 有没有一种方法,我的C#应用​​程序可以等到两个宏都完成运行为止?

C#: C#:

xlApp.Run("first-sub");

Macros: 宏:

Sub first-sub 'Some code lines' Application.OnTime(Now + "00:00:05"), "second-sub" End Sub

Sub second-sub 'Some code lines' End Sub

I tried using Thread.Sleep, it didn't work. 我尝试使用Thread.Sleep,但没有用。 Also, I tried creating a separate macro that runs calls first-sub and waits for 5 seconds. 另外,我尝试创建一个单独的宏,该宏运行调用first-sub的命令并等待5秒钟。 That didn't work either. 那也不起作用。

I am working with an add-in (bloomberg add-in) that calculates the result only after the 'first-sub' has ended. 我正在使用一个插件(bloomberg插件),该插件仅在“ first-sub”结束后才计算结果。 This add-in doesn't calculate results in the middle of the sub. 此外接程序不在子中间计算结果。 So, once the control from the sub comes out, with-in about 5 seconds my results are populated. 因此,一旦子控件出现,大约5秒钟内便填充了我的结果。 Then, I need 'second-sub' to execute. 然后,我需要执行“ second-sub”。 This is the reason, I have to use Application.OnTime and not Application.Wait. 这就是原因,我必须使用Application.OnTime而不是Application.Wait。

So, the following codes didn't work 因此,以下代码不起作用

xlApp.Run("first-sub");            
xlApp.OnTime((DateTime.Now + TimeSpan.FromSeconds(5)).ToString(), "second-sub");

It did run the second-sub, but bloomberg results were not populated. 它确实运行了第二子程序,但是没有填充彭博社的结果。

This is one of many possible solutions: 这是许多可能的解决方案之一:

Sub first-sub
    'Some code lines'
    Application.Wait "00:00:05"
    second-sub
End Sub

This way, you wait 5 seconds, then execute second-sub synchronously, and first-sub ends AFTER the execution of second-sub. 这样,您等待5秒钟,然后同步执行第二个子,第一个子在第二个子的执行后结束。

Another solution is to execute the two subs SEPARATELY: 另一个解决方案是分别执行两个子:

xlApp.Run("first-sub");
Application.Wait "00:00:05"
xlApp.Run("second-sub");

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

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