iT邦幫忙

0

Python win32com 操控 Excel VBA(Private Sub)

  • 分享至 

  • xImage

執行以下code會遇到錯誤

# 開啟 Excel
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
# 開啟 hello.xlsm 活頁簿檔案
wb = excel.Workbooks.Open(Filename=r"Program-V3.xlsm")
# 執行巨集程式
wb.Application.Run("Program-V3.xlsm!Sheet1.CommandButton1_Click")
wb.Save()
wb.Close()
excel.Application.Quit()

com_error                                 Traceback (most recent call last)
<ipython-input-13-015d33d26577> in <module>
      6 # ws = wb.Worksheets('統計分析表')
      7 # 執行巨集程式
----> 8 wb.Application.Run("Program-V3.xlsm!Sheet1.CommandButton1_Click")
      9 wb.Save()
     10 wb.Close()

D:\WPy64-3920\python-3.9.2.amd64\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)

D:\WPy64-3920\python-3.9.2.amd64\lib\site-packages\win32com\client\dynamic.py in _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args)
    307 
    308         def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
--> 309                 result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
    310                 return self._get_good_object_(result, user, resultCLSID)
    311 

com_error: (-2147352567, '發生例外狀況。', (0, 'Microsoft Excel', "無法執行巨集 'BY_CH_PM_Program-V3.xlsm!Sheet1.CommandButton1_Click'。該巨集可能無法在此活頁簿中使用,或者已停用所有巨集。", 'xlmain11.chm', 0, -2146827284), None)

到excel確認 該巨集開頭是:

Private Sub CommandButton1_Click()

個人猜測是因為Private Sub的關係,想請問有什麼辦法能解決次問題呢?

froce iT邦大師 1 級 ‧ 2023-01-06 11:21:58 檢舉
改成public sub?
re.Zero iT邦研究生 5 級 ‧ 2023-01-06 12:18:49 檢舉
你感覺 Private Sub 有問題,可參考:
https://learn.microsoft.com/zh-tw/office/vba/language/reference/user-interface-help/sub-statement
調整看看~
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答