Quantcast
Channel: Bacon Bits
Viewing all articles
Browse latest Browse all 33

Running an Excel Macro from Access (or Another Excel Workbook)

$
0
0

One of the more common questions I get revolves around running an Excel macro from Access. That is, how do you fire an existing Excel macro from Access.

I'll share the code to do that in a moment.

I first want to point out that this code can also come in handy if you need to run an external Excel macro in another workbook. That is to say, while you are working in an Excel file, you can reach out and run a macro in another workbook.

 

OK. Here it is. Simply paste this code in a new module.

 

  1. Sub RunExcelMacro()
  2. Dim xl As Object
  3.  
  4. 'Step 1:  Start Excel, then open the target workbook.
  5.    Set xl = CreateObject("Excel.Application")
  6.     xl.Workbooks.Open ("C:\Book1.xlsm")
  7.  
  8. 'Step 2:  Make Excel visible
  9.    xl.Visible = True
  10.  
  11. 'Step 3:  Run the target macro
  12.    xl.Run "MyMacro"
  13.  
  14. 'Step 4:  Close and save the workbook, then close Excel
  15.    xl.ActiveWorkbook.Close (True)
  16.     xl.Quit
  17.  
  18. 'Step 5:  Memory Clean up.
  19.    Set xl = Nothing
  20.  
  21. End Sub

 

Some notes on the code:

Step 1: Create a new instance of Excel, open the target workbook; the workbook that contains the macro you need to run.

 

Step 2: Making Excel Visible. By default, Excel will open and run in the background (invisible to you). You can set the Visible property to TRUE if you need to see the workbook. If you don't want to see the Excel workbook while the macro is running, simply set the Visible property to FALSE.

 

Step 3: Run the target macro

 

Step 4: Close and save the target workbook. The True argument in xlwkbk.Close(True) indicates that you want the workbook saved after the macro has run. If you do not want to save the target workbook, change this argument to False. Also in Step 4, you quit the Excel application, effectively closing the instance of Excel.

 

Step 5: Release the objects assigned to your variables, reducing the chance of any problems caused by rogue objects that may remain open in memory.


Viewing all articles
Browse latest Browse all 33

Trending Articles