简体   繁体   English

如何使用 Python 运行宏?

[英]How to run a macro with Python?

I want to run a Macro with python.我想用python运行一个宏。 I am doing:我在做:

import win32com.client as w3c

def ejecuntar_macro():
    xlApp_mrapp = w3c.Dispatch("Excel.Application")
    pw_str = str('Plantilla123')
    mrapp = r'D:\Proyectos\Tablero estados\Tablero.xlsm'
    xlApp_mrapp.Visible = True
    xlApp_mrapp.DisplayAlerts = False 
    wb = xlApp_mrapp.Workbooks.Open(mrapp, False, False, None, pw_str)
    xlApp_mrapp.Application.Run("'" + mrapp + "'" + "!Módulo1.guardar_archivo")
    wb.Close(True)
    xlApp_mrapp.Quit()

ejecuntar_macro()

but I keep getting an error:但我不断收到错误消息:

File ".\\ejecucion.py", line 244, in ejecuntar_macro xlApp_mrapp.Application.Run("'" + mrapp + "'" + "!Módulo1.guardar_archivo") File "", line 14, in Run File "C:\\Users\\Ruben\\AppData\\Roaming\\Python\\Python37\\site-packages\\win32com\\client\\dynamic.py", line 314, in ApplyTypes result = self.oleobj.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Ocurrió una excepción.', (0, None, None, None, 0, -2146788248), None)文件“.\\ejecucion.py”,第 244 行,在 ejecuntar_macro xlApp_mrapp.Application.Run("'" + mrapp + "'" + "!Módulo1.guardar_archivo") 文件“”,第 14 行,在运行文件“C: \\Users\\Ruben\\AppData\\Roaming\\Python\\Python37\\site-packages\\win32com\\client\\dynamic.py",第 314 行,在 ApplyTypes 结果 = self.oleobj.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes ) + args) pywintypes.com_error: (-2147352567, 'Ocurrió una excepción.', (0, None, None, None, 0, -2146788248), None)

Please, Can You help me to solve it?.拜托,你能帮我解决吗?。

I do not believe you need to specify the whole file path of the workbook to run the macro.我认为您不需要指定工作簿的整个文件路径来运行宏。 You need to specify whole file path to open the workbook, obviously.显然,您需要指定整个文件路径来打开工作簿。 But once the workbook is open then to run a macro you only need to specify the workbook name.但是一旦工作簿打开然后运行宏,您只需要指定工作簿名称。 So something like the following ...所以像下面这样......

xlApp_mrapp.Application.Run("Tablero.xlsm!Módulo1.guardar_archivo")

Thanks for your answers.感谢您的回答。 I solved the error the follows.我解决了以下错误。 First, I have to say that in my macro I have a code to close the file.首先,我不得不说,在我的宏中,我有一个关闭文件的代码。 I removed this part.我删除了这部分。

the code is:代码是:

import win32com.client as w3c

def ejecuntar_macro():
    xlApp_mrapp = w3c.Dispatch("Excel.Application")
    pw_str = str('Plantilla123')
    mrapp = r'D:\Proyectos\Tablero estados\Tablero.xlsm'
    tablero = 'Tablero.xlsm'
    xlApp_mrapp.Visible = True
    xlApp_mrapp.DisplayAlerts = False 
    wb = xlApp_mrapp.Workbooks.Open(mrapp, False, False, None, pw_str)
    xlApp_mrapp.Application.Run("'" + tablero+ "'" + "!Módulo1.guardar_archivo")
    wb.Close(True)
    xlApp_mrapp.Quit()

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

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