How to run Excel macro from command line (without Worksheet_Open event)?

Can I run the Excel macro from the command line?

I do not want to use the Worksheet_Open event and just open the Excel file.

I need to run a specific macro that exists in Excel WorkBook.

+6
source share
5 answers

Finally, I used VB Script and ran it from the command line. This was my solution:

 Option Explicit LaunchMacro Sub LaunchMacro() Dim xl Dim xlBook Dim sCurPath sCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".") Set xl = CreateObject("Excel.application") Set xlBook = xl.Workbooks.Open(sCurPath & "\MyWorkBook.xlsm", 0, True) xl.Application.Visible = True xl.Application.run "MyWorkBook.xlsm!MyModule.MyMacro" xl.DisplayAlerts = False xlBook.saved = True xl.activewindow.close xl.Quit Set xlBook = Nothing Set xl = Nothing End Sub 
+7
source

Use Windows PowerShell, it has excellent support for interacting with COM.

I have a book c: \ TestBeep.xlsm with a macro called "Test". This is my decryption:

 PS C:\> $app = New-Object -comobject Excel.Application PS C:\> $wb = $app.Workbooks.Open("c:\TestBeep.xlsm") PS C:\> $wb.Name TestBeep.xlsm PS C:\> $app.Run("Test") PS C:\> $app.Quit() 

Optionally, you can add in $app.Visible = $True to make the window look.

+11
source

AutoIt also offers excellent COM support and has many built-in Excel management features. You can compile the script in .EXE and then run it from the command line.

0
source

If you prefer to use C # code, use this template

 void Main() { var oExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); try{ //oExcelApp.Visible = true; var WB = oExcelApp.ActiveWorkbook; var WS = (Worksheet)WB.ActiveSheet; ((string)((Range)WS.Cells[1,1]).Value).Dump("Cell Value"); oExcelApp.Run("test").Dump("macro"); } finally{ if(oExcelApp != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcelApp); oExcelApp = null; } } 
0
source

Thanks! Mehdi your answer worked for me too with a little tweaking. The xl.Application.Visible = True left the zombie / phantom EXCEL.EXE process open using memory (found through the Windows task manager). Using xl.Application.Visible = False instead seems to eliminate the zombies.

0
source

Source: https://habr.com/ru/post/917364/


All Articles