簡體   English   中英

Python:用python運行Excel宏

[英]Python : running Excel macro with python

我需要通過python運行Excel宏,我總是得到以下錯誤:

result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)

在Excel中,它給出以下錯誤:

運行時錯誤1004:無法運行宏“。宏可能在此工作簿中不可用,或者可能禁用所有宏。

我的代碼如下:

xl=win32.Dispatch("Excel.Application")
wb=xl.Workbooks.Open(Filename="Path+MyExcelFile.xlsm", ReadOnly=1)
xl.Visible = True
time.sleep(1)
ws=wb.Worksheets("Sheet1")
ws.Cells(4,2).Value='Value1'
ws.Cells(5,2).Value='Value2'
ws.Cells(1,8).Value='Bool'
time.sleep(10)
xl.Application.Run("MyExcelFile.xlsm!macroname")
result = ws.Cells(3,10).Value
print result
xl.Application.Quit()
del xl

我通過宏安全性啟用了所有宏,並且沒有為特定工作表定義宏。 當然,如果我在Excel中手動運行它,宏工作正常

這對我來說很好。 只需更改宏的路徑和名稱即可。

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()

我試過xl.Application.Run(“macroname”),然后就可以了。 我只打開了一個工作簿和一個獨特的“macroname”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM