Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Excel VBA functions and subs using Python win32com?

My Excel workbook contains VBA subs and macros similar to those below; they sit in Module1.

How to call them using Python win32com module?

Public Sub setA1(ByVal s As String)
    ThisWorkbook.ActiveSheet.Range("A1").Value = s
End Sub

Public Function getA1() As String
    getA1 = ThisWorkbook.ActiveSheet.Range("A1").Value
End Function

Many thanks in advance!

like image 311
Yulia V Avatar asked Feb 06 '13 15:02

Yulia V


People also ask

How do you call a function in a sub in VBA Excel?

To call a Sub procedure from another procedure, type the name of the procedure and include values for any required arguments. The Call statement is not required, but if you use it, you must enclose any arguments in parentheses. Use a Sub procedure to organize other procedures so they are easier to understand and debug.

Can you run an Excel macro through Python?

You can write an Excel macro in python to do whatever you would previously have used VBA for. Macros work in a very similar way to worksheet functions. To register a function as a macro you use the xl_macro decorator. Macros are useful as they can be called when GUI elements (buttons, checkboxes etc.)

Can I use Python instead of VBA in Excel?

Unlike the VBA language used in Excel, data analysis using Python is cleaner and provides better version control. Better still is Python's consistency and accuracy in the execution of code. Other users can replicate the original code and still experience a smooth execution at the same level as the original code.


1 Answers

import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="c:\\temp\\book1.xls",ReadOnly=1)
xl.Application.Run("setA1", '4')
res = xl.Application.Run("getA1")
print res
xl = 0

Just as simple as this ....

like image 50
Yulia V Avatar answered Oct 18 '22 22:10

Yulia V