【问题标题】:VBA macro through Python script通过 Python 脚本实现 VBA 宏
【发布时间】:2020-02-16 07:19:12
【问题描述】:

我正在尝试通过 python 脚本执行宏。当我第一次运行它时它运行正常,但是当我在几分钟后再次运行它时,它会抛出错误

文件“<COMObject <unknown>>”,第 2 行,运行 pywintypes.com_error:
(-2147352567, '发生异常。', (0, None, None, None, 0, -2146827284),无)

我的脚本:

import win32com.client as win32
import  time
excel=win32.Dispatch("Excel.Application")
excel.visible=1
book=excel.Workbooks.open('C:\\Users\\C296442\\Documents\Application07012020.xlsm')
excel.application.run("Application07012020.xlsm!Sheet5.CommandButton12_Click")

【问题讨论】:

  • 猜测:也许您需要关闭工作簿?

标签: python excel vba


【解决方案1】:

我找到了 2 种方法来做到这一点,而且似乎都可以正常工作。

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:\\Users\\rshuell001\\Desktop\\Valuation Code Rollover.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:\Full Location\To\excelsheet.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多