2017-07-19 172 views
0

我在python中运行如下代码来打开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) 

我在做什么错

+0

你是否尝试通过手动给出完整路径来运行代码,只是为了检查它的工作? –

+0

它只有当我做了绝对路径的正斜杠时才起作用。但是,这不能作为这个文件可能部署到其他人的计算机上。因此,我在看相对路径 – Adam

+0

hi @ YowE3K请问在开放语句中你的意思是状态完整路径?是不是问题在这里,我不能将Excel文件传入workbooks.open()? – Adam

回答

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.xlsbfileDir变量。 (虽然..是指父目录,.指现有目录。)

即使用:

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

hihi, 我编辑我的代码,以便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); XL = win32.client.Dispatch( 'Excel.Application') xl.Workbooks.Open(文件名=文件名) 德尔XL 但即时仍得到相同的错误: '异常发生', (0,'Microsoft Excel',“对不起,我们找不到C:\\ Users \\ adrlee \\ Desktop \\ Python文件\\ Automation \\ Powerpoint \\ Automation.xlsb。 – Adam

0

感谢您的意见和提示的家伙!我设法终于搞定了:

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