Use Python to Write VBA Script?

后端 未结 1 696
傲寒
傲寒 2020-12-05 12:42

This might be a bit of a stretch, but is there a possibility that a python script can be used to create VBA in MS Excel (or any other MS Office product that uses VBA) using

相关标签:
1条回答
  • 2020-12-05 12:56

    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 win32
    
    import comtypes, comtypes.client
    
    xl = win32.gencache.EnsureDispatch('Excel.Application')
    xl.Visible = True
    ss = xl.Workbooks.Add()
    sh = ss.ActiveSheet
    
    xlmodule = ss.VBProject.VBComponents.Add(1)  # vbext_ct_StdModule
    
    sCode = '''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.

    0 讨论(0)
提交回复
热议问题