简体   繁体   中英

From VBA to Python and back again to Excel

I am trying to make an automated program using Excel and Python 3.7.1.

  • Starting from an Excel sheet, the user is supposed to click a button which
    is been assigned a Macro (actually it is an ActiveX Controls Command Button).
  • This Macro runs Python and closes the Excel window.
  • The Python script reads data from another .xlsx file, makes a regression and stores the results into a pandas DataFrame.

What I am trying to do now is writing this DataFrame into a second sheet (already created, but empty) in the .xlsm file that ran Python.

I have tried different ways, looked for lots of help on the internet but nothing seems to work. I have also read about the "vbaProject.bin", but I can't extract the content from the file calling it in the Command prompt.

Either the data is displayed as expected but the button is no longer "clickable", or the data is not displayed at all. Sometimes the file is not even available cause its type has been changed by python.

I have used both openpyxl and xlsxwriter but in vain. Here's one of the pieces of code:

wb = load_workbook('PythonLauncher.xlsm', keep_vba=True)
writer = pd.ExcelWriter('PythonLauncher.xlsm', engine=openpyxl)
writer.book = wb
DtFrm.to_excel(writer, writer.book.sheetnames[1], columns=None, index=False)
writer.save()
writer.close()

The optimal result would be to obtain the DataFrame in the second sheet of the .xlsm file without losing the click functionality.

You can easily run Excel/VBA from Python. Below are two examples to do exactly this same thing.

from __future__ import print_function
import unittest
import os.path
import win32com.client

class ExcelMacro(unittest.TestCase):
    def test_excel_macro(self):
        try:
            xlApp = win32com.client.DispatchEx('Excel.Application')
            xlsPath = os.path.expanduser('C:\\your_path\\test.xlsb')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('Macro1')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
if __name__ == "__main__":
    unittest.main()

import os
import win32com.client

#Launch Excel and Open Wrkbook
xl=win32com.client.Dispatch("Excel.Application")  
xl.Workbooks.Open(Filename="C:\\your_path\\test.xlsm") #opens workbook in readonly mode. 

#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname") 

#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit() 

#Cleanup the com reference. 
del xl

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