打开excel文件,从python中的相对文件路径运行宏

时间:2017-07-19 07:29:04

标签: python excel-vba vba excel

我在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)

我做错了什么

2 个答案:

答案 0 :(得分:1)

感谢您的评论和提示!我设法最终做对了:

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");

答案 1 :(得分:0)

如果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')