9

Do anybody know a method to call Excel VBA function in Python.

In my case, I would like my program which is programmed in Python produce an output in Excel by calling a function which is created in Visual Basic.

Is there any method on doing that?

Community
  • 1
  • 1
maximus
  • 131
  • 1
  • 2
  • 10

1 Answers1

15

In order to do this you will need to use pywin32, and use the excel com interface.

Please review the documentation for the Excel Com Interface:

Please note this has been asked before Running an Excel Macro via Python

The code below is a slight modification of the original.

import os
import win32com.client

#Launch Excel and Open Wrkbook
xl=win32com.client.Dispatch("Excel.Application")  
xl.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm") #opens workbook in readonly mode. 

#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname") 

#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit() 

#Cleanup the com reference. 
del xl

Good Luck.

Community
  • 1
  • 1
Luis Ramirez
  • 414
  • 3
  • 7