【问题标题】:Appliying a VBA macro to an Excel file using win32com python library使用 win32com python 库将 VBA 宏应用于 Excel 文件
【发布时间】:2020-01-22 21:36:26
【问题描述】:

我正在尝试使用 python 和 win32com 库应用 VBA 宏,其想法是创建一个固定的 excel 文件,存储一个宏然后运行它。我从这里得到了这个想法:https://redoakstrategic.com/pythonexcelmacro/

当脚本必须使用 xlsm 文件并使用 Application.Run() 运行宏时,就会出现问题。我的代码是:

import pandas as pd 
import win32com.client 
import os

#creating the dataframe
df = df1=pd.read_excel ("normal_excel_file.xlsx", index_col=0)
filename = "normal_excel_file.xlsx"
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
df.to_excel(writer, sheet_name='data', index=False)

#copiying and renaming the file to xlsm
shutil.copy("normal_excel_file.xlsx", "(1)normal_excel_file.xlsx")
os.rename("(1)normal_excel_file.xlsx", "macros_excel_file.xlsm")

#adding the macro to the workbook
filename_macro = r"C:\Users\John\Desktop\Python_scripts\Running VBA Macro\macros_excel_file.xlsm"
workbook = writer.book
workbook.filename = filename_macro
workbook.add_vba_project('vbaProject.bin')
writer.save()

还有冲突的部分:

 if os.path.exists(filename_macro):
        xl = win32com.client.Dispatch('Excel.Application')
        xl.Workbooks.Open(Filename = filename_macro, ReadOnly=1)

        #assuming that there is only one macro, and is stored as "ThisWorkbook.Macro1" in the file

        xl.Application.Run("ThisWorkbook.Macro1") #I also try using only "Macro1" and the whole path of the file
        xl.Application.Quit()
        del xl

我得到下一个错误。首先是错误信息:

com_error: (-2147352567, 'An exception occurred.', (0, 'Microsoft Excel', 'The "ThisWorkbook.Macro1" macro cannot be executed. The macro may not be available in this book or all of them may have been disabled. the macros. ',' xlmain11.chm ', 0, -2146827284), None)

以及整个错误文本:

com_error                                 Traceback (most recent call last)
<ipython-input-16-6e91b8d2f622> in <module>
      3     xl = win32com.client.Dispatch('Excel.Application')
      4     xl.Workbooks.Open(Filename = filename_macro, ReadOnly=1)
----> 5     xl.Application.Run("ThisWorkbook.Macro1")
      6     xl.Application.Quit()
      7     del xl

~\Anaconda3\lib\site-packages\win32com\client\dynamic.py in Run(self, Macro, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, Arg11, Arg12, Arg13, Arg14, Arg15, Arg16, Arg17, Arg18, Arg19, Arg20, Arg21, Arg22, Arg23, Arg24, Arg25, Arg26, Arg27, Arg28, Arg29, Arg30)

~\Anaconda3\lib\site-packages\win32com\client\dynamic.py in _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args)
    285 
    286         def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
--> 287                 result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
    288                 return self._get_good_object_(result, user, resultCLSID)
    289 

com_error: (-2147352567, 'An exception occurred.', (0, 'Microsoft Excel', 'The "ThisWorkbook.Macro1" macro cannot be executed. The macro may not be available in this book or all of them may have been disabled. the macros. ',' xlmain11.chm ', 0, -2146827284), None)

我进入 Microsoft Office 中的信任中心,并允许所有宏类型 (https://support.office.com/en-us/article/enable-or-disable-macros-in-office-files-12b036fd-d140-4e74-b45e-16fed1a7e5c6?ui=en-US&rs=en-US&ad=US)。但是错误继续发生

如果有人知道如何解决它会很棒

谢谢大家

【问题讨论】:

  • 如果在 Excel 中打开创建的 xlsm 文件,在 VBA 开发人员模式下,会出现错误吗?如果没有,是否存在名为 Macro1 的宏以及名为 ThisWorkbook 的工作簿对象?
  • 无法编写 Python win32com 函数的宏还有什么作用?
  • 嗨@jmcnamara,当我尝试访问 xlsm 文件时显示此消息 ///“Excel 无法打开文件 'filename.xlsm',因为文件格式或文件扩展名无效。验证文件没有损坏并且文件扩展名与文件的格式匹配。”/// 当返回并将我的文件重新转换为 xlsx 时,我可以正常打开它,但由于是 xlsx 格式,我无法检查宏
  • @Parfait 例如下拉单元格的可能性或 Excel 中数据透视表的拖放构造系统。我这样做是为了向非技术人员报告
  • Excel 对象模型的任何内容都可以用 Python 等 COM 连接语言处理。请记住,VBA 也建立 COM 连接,与 Excel 无关。在 Tools\References 下,首先检查 VBA 对象。因此,您应该能够翻译甚至避免.xlsm 的安全问题。

标签: python excel win32com


【解决方案1】:

因为.xlsx.xlsm 是根本不同类型的二进制文件,你不能简单地使用行来复制和重命名:

shutil.copy("normal_excel_file.xlsx", "(1)normal_excel_file.xlsx")
os.rename("(1)normal_excel_file.xlsx", "macros_excel_file.xlsm")

(奇怪的是,您的教程链接没有显示 Pandas 生成的.xlsx 文件如何在后续附加的宏步骤中变成.xlsm。)

改为使用 Excel 编写器对象来迁移宏并另存为 .xlsm。另外,在 writer 对象上使用with 上下文管理器可以在处理后有效地关闭 i/o 对象。

# creating the dataframe
path = "C:\Users\John\Desktop\Python_scripts\Running VBA Macro"
filename = "normal_excel_file.xlsx"
filename_macro = "macros_excel_file.xlsm"

df = pd.read_excel(filename, index_col=0)
with pd.ExcelWriter(filename, engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='data', index=False)
    workbook = writer.book
    workbook.filename = filename_macro
    workbook.add_vba_project('vbaProject.bin')
    writer.save()

# RUN MACRO
if os.path.exists(os.path.join(path, filename_macro)):
    wb = xl.Workbooks.Open(Filename = filename_macro, ReadOnly=1)
    xl.Application.Run("ThisWorkbook.Macro1")
    xl.Application.Quit()

【讨论】:

  • 太棒了,也很有意义。非常感谢。有一件事,当我尝试运行您的代码时,我收到以下错误 /// Invalid extension for engine 'xlsxwriter': 'xlsm' /// in the "# added the macro to the workbook" 部分。我会在一天结束时,在几个小时内调查它,但也许你可以说明我
  • 看到这个solution,显然你根本不需要shutil,因此SaveAs。查看我的编辑。
  • 杀手。有用。我很感激。你现在是我的英雄。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 2013-05-19
  • 2015-04-12
  • 2020-12-01
相关资源
最近更新 更多