Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to run Excel macros from command line or batch file?

I have an Excel VBA macro which I need to run when accessing the file from a batch file, but not every time I open it (hence not using the open file event). Is there a way to run the macro from the command line or batch file? I'm not familiar with such a command.

Assume a Windows NT environment.

like image 439
Polymeron Avatar asked Jan 12 '10 16:01

Polymeron


People also ask

How do you create a macro in a batch file?

The basic structure of the macro definition: Set _macro=For /l %%n in (1 1 2) do if %%n==2 (Echo Main MACRO goes here.) else setlocal enableDelayedExpansion ^& Set argv=, %_macro% arg1 arg2 :: The macro will expand to: :: for /l %%n in (1 1 2) do if %%n==2 (Echo Main MACRO goes here.)


1 Answers

You can launch Excel, open the workbook and run the macro from a VBScript file.

Copy the code below into Notepad.

Update the 'MyWorkbook.xls' and 'MyMacro' parameters.

Save it with a vbs extension and run it.

Option Explicit  On Error Resume Next  ExcelMacroExample  Sub ExcelMacroExample()     Dim xlApp    Dim xlBook     Set xlApp = CreateObject("Excel.Application")    Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls", 0, True)    xlApp.Run "MyMacro"   xlApp.Quit     Set xlBook = Nothing    Set xlApp = Nothing   End Sub  

The key line that runs the macro is:

xlApp.Run "MyMacro"

like image 142
Robert Mearns Avatar answered Sep 17 '22 16:09

Robert Mearns