Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call python script on excel vba?

Trying to call a python script on Vba and I am a newb. I tried converting the main script to an exe using py2exe and then calling it from VBA (shell) but the main script calls other scripts therefore it becomes complicated and I messed it up (my exe is not functional). Besides, the the main script is a large file and I do not want to revise it a lot.

Bottomline, is there a way to call the main script from excel vba, without converting the script to an exe file.

So far, I tried:

RetVal = Shell("C:\python27\python.exe " & "import " & "C:\\" & "MainScriptFile") 

It starts python.exe but does nothing else. Then I tried:

RetVal = Shell("C:\Windows\System32\cmd.exe " & "python " & "C:\\Python27\\hello.py") 

It starts command prompt but does not even start python.

P.S. I checked all the related questions in the forum, they do not solve my prob.

like image 291
Ege Ozlem Avatar asked Aug 08 '13 20:08

Ege Ozlem


People also ask

Can I use Python code in VBA?

Everything you can write in VBA can be done in Python.

Can Excel execute a Python script?

In short, executing Python via Excel provides those with sufficient experience in the language with an avenue to efficiently communicate and visualize their data in a way that most people can see and understand.


1 Answers

Try this:

RetVal = Shell("<full path to python.exe> " & "<full path to your python script>") 

Or if the python script is in the same folder as the workbook, then you can try :

RetVal = Shell("<full path to python.exe> " & ActiveWorkBook.Path & "\<python script name>") 

All details within <> are to be given. <> - indicates changeable fields

I guess this should work. But then again, if your script is going to call other files which are in different folders, it can cause errors unless your script has properly handled it. Hope it helps.

like image 151
Rajgopal C Avatar answered Sep 20 '22 20:09

Rajgopal C