简体   繁体   English

从VBA到Python,然后再回到Excel

[英]From VBA to Python and back again to Excel

I am trying to make an automated program using Excel and Python 3.7.1. 我正在尝试使用Excel和Python 3.7.1制作自动化程序。

  • Starting from an Excel sheet, the user is supposed to click a button which 从Excel工作表开始,用户应单击一个按钮,
    is been assigned a Macro (actually it is an ActiveX Controls Command Button). 被分配了一个宏(实际上它是一个ActiveX控件命令按钮)。
  • This Macro runs Python and closes the Excel window. 该宏运行Python,然后关闭Excel窗口。
  • The Python script reads data from another .xlsx file, makes a regression and stores the results into a pandas DataFrame. Python脚本从另一个.xlsx文件读取数据,进行回归并将结果存储到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. 我现在想要做的就是将此DataFrame写入运行Python的.xlsm文件中的第二张表(已创建,但为空)。

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. 我还阅读了有关“ vbaProject.bin”的信息,但是我无法从命令提示符下调用它的文件中提取内容。

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. 有时文件甚至不可用,因为它的类型已被python更改。

I have used both openpyxl and xlsxwriter but in vain. 我曾经用过openpyxl和xlsxwriter但徒劳。 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. 最佳结果将是在.xlsm文件的第二页中获取DataFrame而不丢失单击功能。

You can easily run Excel/VBA from Python. 您可以从Python轻松运行Excel / VBA。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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