Home » excel » 20 minute Excel macro to run from c# Winform

20 minute Excel macro to run from c# Winform

Posted by: admin April 23, 2020 Leave a comment

Questions:

We have a macro that takes approximately 20 minutes to complete.
We’ve got a c# winform that our user has access to – it contains a “Run Macro” button.
I’d like it so that the user can hit the button and then actually close the form and then in 20mins time see the output from the macro in a pre-defined directory.

Is it simply a case of creating a delegate and letting the delegate run the macro or is the above not a trivial matter?

Couple of ideas which might be viable:

  • Just hide the form after the user presses the button? Drawback is that the macro will still be tying up the user’s cpu within an instance of Excel?
  • Could the winForm on UserX’s pc somehow kick-off a program to run on our ‘Excel’ server? This sounds far fetched but maybe someone can help.
  • Similar to the above maybe on the Excel server I could create a small daemon console app that is scheduled to run every 2 seconds and check a table on a shared db to see if any macros need running. The user’s winform could update this control table and the daemon then goes to work.
How to&Answers:

Yes it is simple.

Use C# to launch a VBS File. The code will be something like

System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\MyScript.vbs");

The above code will launch the VBScript with no prompts or errors and no shell logo.

Next Step is to create a vbs file.

Open Notepad and paste this code and save it as a MyScript.vbs file

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Test.xls", 0, True)
xlApp.Run "TestMacro"
xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing