Use Python to Write VBA Script? Use Python to Write VBA Script? vba vba

Use Python to Write VBA Script?


Yes, it is possible. You can start looking at how you can generate a VBA macro from VB on that Microsoft KB.

The Python code below is illustrating how you can do the same ; it is a basic port of the first half of the KB sample code:

import win32com.client as win32import comtypes, comtypes.clientxl = win32.gencache.EnsureDispatch('Excel.Application')xl.Visible = Truess = xl.Workbooks.Add()sh = ss.ActiveSheetxlmodule = ss.VBProject.VBComponents.Add(1)  # vbext_ct_StdModulesCode = '''sub VBAMacro()       msgbox "VBA Macro called"      end sub'''xlmodule.CodeModule.AddFromString(sCode)

You can look at the visible automated Excel macros, and you will see the VBAMacro defined above.


The top answer will only add the macro, if you actually want to execute it there is one more step.

import win32com.client as win32xl = win32.gencache.EnsureDispatch('Excel.Application')xl.Visible = Truess = xl.Workbooks.Add()xlmodule = ss.VBProject.VBComponents.Add(1)xlmodule.Name = 'testing123'code = '''sub TestMacro()    msgbox "Testing 1 2 3"    end sub'''xlmodule.CodeModule.AddFromString(code)ss.Application.Run('testing123.TestMacro')

Adding a module name will help deconflict from any existing scripts.