簡體   English   中英

打開Excel文件以從python中的相對文件路徑運行宏

[英]Open excel file to run macro from relative file path in python

我在python中運行以下代碼以打開excel並運行宏。 基本上我的python腳本位於

C:\Users\adrlee\Desktop\Python files\Automation

而我的Excel VBA文件(Automation.xlsb)位於

C:\Users\adrlee\Desktop\Python files\Automation\Powerpoint

我正在運行這段代碼

fileDir = os.path.dirname(os.path.realpath('__file__'));

filename = os.path.join(fileDir, '../Powerpoint/Automation.xlsb')
filename = os.path.abspath(os.path.realpath(filename))
print(filename);

if os.path.exists("Powerpoint/Automation.xlsb"):
    xl=win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(filename)
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl

print("Powerpoint generated");

但我遇到錯誤

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find C:\\Users\\adrlee\\Desktop\\Python files\\Powerpoint\\Automation.xlsb. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)

我究竟做錯了什么

謝謝大家的評論和提示! 我終於做到了:

fileDir = os.path.dirname(os.path.realpath('__file__'));

filename = os.path.join(fileDir, './Powerpoint/Funnel Automation.xlsb')
print(filename);


xl=win32com.client.Dispatch('Excel.Application')
xl.Workbooks.Open(Filename = filename)
del xl

print("Powerpoint generated");

如果fileDir包含

C:\Users\adrlee\Desktop\Python files\Automation\

然后加入..\\Powerpoint\\Automation.xlsb將得到

C:\Users\adrlee\Desktop\Python files\Automation\..\Powerpoint\Automation.xlsb

相當於

C:\Users\adrlee\Desktop\Python files\Powerpoint\Automation.xlsb

因為..等效於父目錄,而...\\Python files\\Automation的父目錄是...\\Python files


您的問題指出Excel文件實際上是

C:\Users\adrlee\Desktop\Python files\Automation\Powerpoint\Automation.xlsb

因此,您實際上應該將.\\Powerpoint\\Automation.xlsb加入到fileDir變量中。 (雖然..指代父目錄, .指代現有目錄。)

即使用:

filename = os.path.join(fileDir, './Powerpoint/Automation.xlsb')

暫無
暫無

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

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