Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way I can call Excel VBA function through Python? [duplicate]

Tags:

python

excel

vba

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?

like image 649
maximus Avatar asked Jun 01 '16 05:06

maximus


People also ask

Can you call VBA from Python?

A python library called xlwings allows you to call Python scripts through VBA and pass data between the two.

Can Python run VBA macros?

Can Python do everything VBA can? Everything you can write in VBA can be done in Python. This page contains information that will help you translate your VBA code into Python. Please note that the Excel Object Model is part of Excel and documented by Microsoft.

Can I use Python instead of VBA in Excel?

Yes, absolutely! VBA is commonly used to automate Excel with macros, add new user defined worksheet functions (UDFs) and react to Excel events. Everything you would previously have done in Excel using VBA can be achieved with Python. Using Python as a VBA replacement has many benefits and is usually faster than VBA!


1 Answers

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.

like image 126
Luis Ramirez Avatar answered Oct 16 '22 01:10

Luis Ramirez