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

Yulia V picture Yulia V · Feb 6, 2013 · Viewed 13.5k times · Source

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!

Answer

Yulia V picture Yulia V · Feb 6, 2013
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 ....