Is it possible to run a macro in Excel from external command?

后端 未结 3 1485
无人共我
无人共我 2021-01-07 12:31

Let\'s say I want to program a VBA code in an external program that opens an Excel file, runs a macro, saves (and say yes to any pop up windows), and close Excel. Is it poss

3条回答
  •  臣服心动
    2021-01-07 13:25

    I can think of several ways to do this.

    You can start excel by creating a file with NotePad or a similar text editor.
    
    Here are some steps:
    
        Launch NotePad
        Add the following line of text. Replace test.xlsm with the name and path for your file:
        start Excel.exe "C\test.xlsm"
        Save the file as "Test.bat". 
        Run the batch file.
        The batch file should launch Excel and then open your file. The code in your workbook should run
    

    OR

    Again, using Notepad.

    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
    

    Or, this.

    'Code should be placed in a .vbs file
    Set objExcel = CreateObject("Excel.Application")
    objExcel.Application.Run "'C:\Users\Ryan\Desktop\Sales.xlsm'!SalesModule.SalesTotal"
    objExcel.DisplayAlerts = False
    objExcel.Application.Quit
    Set objExcel = Nothing
    

    Now, this isn't 'an external command', but the Windows Task Scheduler will do a nice job of opening that file for you, and once it is opened, you can run a tiny script like the one you see below.

    Private Sub Workbook_Open()
       Call CommandButton1_Click
    End Sub
    

    https://www.sevenforums.com/tutorials/11949-elevated-program-shortcut-without-uac-prompt-create.html

提交回复
热议问题