简体   繁体   中英

xlsxwriter python how to execute VBA function in python and export as .xlsx

I've extracted and imported a vba function (autofit all rows) into my python xlsxwriter script. If I open the.xlsm document, I can use the macro via Alt+F8 and it works as expected. But, I'd like to run the macro within python, then export the file as.xlsx

Here is my macro:

Sub AutoFitAll()
     
    Application.ScreenUpdating = False
    Dim wkSt As String
    Dim wkBk As Worksheet
    wkSt = ActiveSheet.Name
    For Each wkBk In ActiveWorkbook.Worksheets
        On Error Resume Next
        wkBk.Activate
        Cells.EntireColumn.AutoFit
    Next wkBk
    Sheets(wkSt).Select
    Application.ScreenUpdating = True
     
End Sub

Here is my command prompt vbaProject.bin extraction

C:\Users\username\Downloads> python C:\file\location\vba_extract.py macro\file\location\site_status_macro.xlsm
Extracted: vbaProject.bin

Here is my code importing pandas dataframes and adding them to seperate sheets. The last part of my python script is not working -- the script runs fine, but when I open the document, the macro has clearly not been executed.

import pandas as pd
import win32com.client as win32

df1 = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
df2 = pd.DataFrame(data={'col3': [5, 6], 'col4': [7, 8]})
df3 = pd.DataFrame(data={'col5': [9, 10], 'col6': [11, 12]})

path = 'C:/Users/username/Downloads/' 
filename = path + 'final_export.xlsx'
filename_macro = path + 'final_export.xlsm'

with pd.ExcelWriter(filename, engine='xlsxwriter') as writer:        
    names = ['Sheet1', 'Sheet2', 'Sheet3']
    dfs = [df1, df2, df3]
    
    for df, name in zip(dfs, names): df.to_excel(writer, sheet_name=name)
 
    workbook = writer.book
    
    workbook.filename = filename_macro
    workbook.add_vba_project(path + 'vbaProject.bin')


xl = win32.Dispatch('Excel.Application')
xl.Workbooks.Open(Filename=filename_macro, ReadOnly=1)
xl.Application.Run("'final_export.xlsm'!AutoFitAll")
xl.Application.Quit()
del xl

The last part isn't working. I've successfully imported my macro, but now i want to run it to autofit all rows. how do I run this macro in python? I'd like to run it in python, and then export it to.xlsx file.

Thanks so much for any and all help!

Please try using package xlwings .
Install it pip install xlwings .

import xlwings
excel_app = xlwings.App(visible=True, add_book=False)
excel_book = excel_app.books.open("final_export.xlsm")
run_macro = excel_book.app.macro('Module1.AutoFitAll')
run_macro()
excel_app.quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM