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!
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.
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.)
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.
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 ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With