python是否可以在excel中添加、运行和删除一个VBA宏而不需要中间的保存步骤?

6 人关注

我有一个长期运行的Python流水线,生成一个pandas数据框架。简而言之,我想

  • Display the pandas dataframe in excel
  • Add & run VBA macro
  • Remove VBA macro and save the (newly formatted) output as .xslx
  • 挑战在于,我无法弄清楚如何做到这一点 没有一个中间的保存为 xlsm 的文件 步骤,这在向 .xlsx 文件添加VBA宏时显然是需要的。由于这样做效率很低,我想摆脱这个中间步骤。

    Here is the code:

    1.在excel中显示pandas数据框架。

    with pd.ExcelWriter('output.xlsx') as writer:
         df_results.to_excel(writer, index = False, sheet_name = "Sheet1")
         #...see below
    

    2A.添加宏并指定.xlsm-filename,以便编写者可以持有宏。

         #... see above
         writer.book.filename = 'output.xlsm'           # Add .xlsm filename
         writer.book.add_vba_project('VBA_script.bin')  # This adds my macro
         writer.save()                                  # How to get rid of this step?
    

    2B.运行宏

    xl = win32com.client.Dispatch("Excel.Application")  # Set up excel
    xl.Workbooks.Open(Filename = 'output.xlsm')         # Open .xlsm file from step 2A
    xl.Application.Run("Module1.Main")                  # Run VBA_macro.bin
    

    3.删除宏并保存为.xlsx

    wb = xl.ActiveWorkbook
    xl.DisplayAlerts = False
    wb.DoNotPromptForConvert = True
    wb.CheckCompatibility = False
    wb.SaveAs('final_outfile.xlsx', FileFormat=51, ConflictResolution=2) # Macro disapears here
    xl.Application.Quit()
    del xl
    xl = None
    

    Is it possible to do this without intermediate .xlsm step & with shorter code?

    How to add, run & remove a VBA macro in an excel context without intermediate saving steps using python?

    5 个评论
    你需要将代码添加到相关的工作簿中吗?否则你应该可以把代码放在一个单独的(可能是永久存在的).xlsm中,然后从那里修改你的.xlsx。
    我想过了--万一这里的问题的答案变成了 "不",就会归结为这一点。
    为什么不把宏代码放在第二个工作簿中?
    另外,什么创造了 VBA_script.bin ,有没有一个Python库来做这个?
    是的,该脚本被称为VBA_extract.py
    python
    vba
    excel
    pandas
    sudonym
    sudonym
    发布于 2018-04-17
    1 个回答
    Ricardo A
    Ricardo A
    发布于 2018-07-13
    已采纳
    0 人赞同

    是的,创建实例,使用内置的VBA代码导入,运行宏,保存为xlsx以删除宏。

    xl = win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Add
    wb = xl.ActiveWorkbook
    wb.VBProject.VBComponents.Import "Full Path\VBA_script.bin"
    xl.Application.Run("Module1.Main")
    xl.DisplayAlerts = False
    wb.DoNotPromptForConvert = True
    wb.CheckCompatibility = False