Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Launch an Excel macro from command line (Without Worksheet_Open Event)?

Tags:

excel

cmd

vba

Is it possible to launch an Excel Macro from command line?

I don't want to use the Worksheet_Open event and just open the Excel File.

I need to launch specific macro that exists in the Excel WorkBook.

like image 371
M3HD1 Avatar asked Jun 04 '12 13:06

M3HD1


People also ask

How do I run a macro from command line?

Place a cursor inside the procedure and press F5 to run it. The macro should run perfectly without any runtime errors if we have to run it successfully from the command line.

How do I open a macro in Excel without running?

Opening Without Automatic MacrosOpen Excel, go to the File menu, click "Open" and locate your file. Hold down the "Shift" key while you click "Open," and continue holding it until the workbook finishes loading.

How do I run a macro line by line in Excel?

Pressing F8 will let you step through the macro code one line at a time. Edit - This will open the Visual Basic Editor and let you edit the macro code as needed. Once you've made changes, you can press F5 to run the macro from the editor.


2 Answers

Use the Windows PowerShell, it has excellent COM interop support.

I have the workbook c:\TestBeep.xlsm with a macro called "Test". This is my transcript:

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 visible.

like image 59
Govert Avatar answered Sep 19 '22 12:09

Govert


I finally created a VB Script and launched it from the command line:

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 
like image 45
M3HD1 Avatar answered Sep 20 '22 12:09

M3HD1