Can't run Python from Excel (xlwings) - python

I'm quite new to xlwings and I'm runing code from VBA in order to excecute a python script that writes some text in Excel.
The problem is when I run the VBA code, it seems to excecute python but my excel sheet doesn't change.
However, if I run the python script from python, it works just fine, even if the Excel file is already open.
VBA code is the following:
Sub Botón1()
Dim obj As Object
Dim pyexe, pyscript As String
Set obj = VBA.CreateObject("Wscript.Shell")
pyexe = """C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\python.exe"""
pyscript = "C:\Users\xxx\Documents\Prueba.py"
obj.Run pyexe & pyscript, 1, True
End Sub
And python code is the following:
import xlwings as xw
wb = xw.Book('Libro1.xlsm')
sht = wb.sheets['Hoja1']
sht.range('A1').value = 'Hi!'
Both files (Libro1.xlsm and Prueba.py) are saved inside the same folder.
When I run excel macro it opens the cmd prompt but nothing happens in Excel spreasheet.
I have not installed xlwings add in, but I believe it is not necessary to do it, in order to do what I'm trying to do.
Can you please help me find what could be wrong?

I was reading this article:
https://devblogs.microsoft.com/scripting/how-can-i-get-the-command-window-to-stay-open-after-running-a-command-line-tool/
And it explains using .run is equivalent to calling Cmd.exe.
If I open cmd I just need to write my python file name with .py extension to run it.
So I figured out "pyexe" is not necessary.
The solution:
Sub Botón1_Haga_clic_en()
Dim obj As Object
Set obj = CreateObject("Wscript.Shell")
obj.Run "C:\Users\xxx\Documents\Prueba.py", 1, True
End Sub

Related

Running python script using Outlook VBA

Im trying to run a python script using Outlook Vba. When I run the below code. A python icon appears in the taskbar for a second and disappears. When in fact it should open a dialogue box and prompt me to enter folder name. After which it should run the rest of the script as usual.
Please help me run this script from outlook as I regularly do by double clicking the .py file.
Sub runpythonscript()
Dim Path As String
Path = "python C:\Doc Management\Exstream_Reconciliation.py"
Shell(Path)
End Sub
VBA (nor Outlook) doesn't provide anything for debugging such cases. The best what you could do is to add log statements to the python script where you could output everything what happens in the code. Analyzing log files you will be able to figure the cause of the problem.
You have a space in the file name. It must be quoted.
Ok this is the solution for anyone looking
Sub RunPyFileFromMacroViaCmd()
Dim Path As String
Dim filepath As String
filepath = """C:\Doc Management\Exstream_Reconciliation.py"""
Path = "cmd /k" & filepath
Shell (Path)
End Sub

VS terminal just outputting two directories?

I am writing a small script to create an Excel workbook with new sheets.
But every time I try and run it the terminal window opens and just shows:
& "C:/Program Files/Python39/python.exe" "c:/Users/Jerome/Desktop/VS Code Projects/Python/Excel workbook/excel_sheet.py"
I am not sure what this means?
import xlwt
from xlwt import Workbook
# This creates the workbook
wb = Workbook()
# the add_sheet() method is used to create a sheet
sheet1 = wb.add_sheet('Sheet 1')
sheet1.write(1, 0, "Chris Smith")
# this saves the workbook
wb.save('new-sheet.xlsx')
It is not an error. It is a command that runs your code with python interpreter. For example if you put a print('end') at the end of your code you can see the print result after this line.
I assume you run the code by clicking on the top right run button in vscode or some other editors. They write this command in the terminal to run your code with python. It is not an error.
"C:/Program Files/Python39/python.exe" this part is the path to python exe file. and "c:/Users/Jerome/Desktop/VS Code Projects/Python/Excel workbook/excel_sheet.py" is the path to the file of your code.
When you run this code open the folder your code exists in. You have to see a new file named new-sheet.xlsx been created. (also I ran your code everything is ok).
If you have any questions please ask.

Simple way of calling a Machine Learning Python script from Excel with out using add-ins

I am stuck in a major pickle where I have some automation in VBA in Excel and need to pass a list of words to a Python script that is running a machine learning algorithm (where it classifies a request). This script will provide a string output (request category) that I need to receive in VBA again.
I have walked through countless methods of using pyxll or xlwings but unfortunately, these will not work for me as the excel file and python file will be in SharePoint being used by different members and I am sure all of them will not be having these add-ins installed.
I found a method of passing the argument (list of words) to a test Python script using command line. The test Python script is able to receive it. Here is the code sample
import sys
script_name = sys.argv[0]
text= sys.argv[1]
print('text - ',sys.argv)
But when I try to use the machine learning script, let's say, to read and export a dataset then it does not work.
My ultimate goal is to run 2 python function:
a function to train my classifier
a function that takes this list of words from VBA, runs the predictive algo and gives back the output (a string).
Can someone maybe help me with it? This is the first time I am working with something cross-platform. If it helps my ML algo is running perfectly well in the Python environment, it is the connection with VBA that needs to be sorted out.
FOR EXAMPLE:
I wrote a test script to see if I can pass my request to Python script and then the python script loads a dataset (to see if this functionality is working or not) and creates a file and writes something in it.
Here is the VBA code:
Sub SampleCall()
'declare var
Dim objShell As Object
Dim PythonExe, PythonScript As String
Dim PythonArg As String, oCmd As String
'create a new shell obj
Set objShell = VBA.CreateObject("Wscript.Shell")
'provide the file path to the python exe
PythonExe = """C:\Users\I547565\AppData\Local\Microsoft\WindowsApps\python.exe"""
'provide file path to python script
PythonScript = """C:\Users\I547565\SAP SE\Headcount Control Tower for Services - Headcount Control Tower\Control Tower - Automation\Resources\Artificial Intelligence\rough.py"""
PythonArg = "I love Europe"
MsgBox PythonArg
objShell.Run PythonExe & Chr$(32) & PythonScript & Chr$(32) & PythonArg
End Sub
ANd here is the python script:
import sys
script_name = sys.argv[0]
text= sys.argv[1]
print('text - ',sys.argv)
input('press enter to continue...')
from pathlib import Path
sysPath = str(Path.home())
rawDataPath = sysPath + "\folder\XRdata.xlsx"
import pandas as pd
df = pd.read_excel('XRdata.xlsx', sheet_name='data')
print(df.head())
f= open("output.txt","w+")
f.write('category')
f.close()
input('press enter to close...')
If I run the python script independently, i get a file named output.txt in my folder. But when I run this script from VBA, I am able to see the "I love Europe" on the console but the rest of the code does not give me the output that is the txt file is not generated.
Please help before I rip my hair out!!!

VBA script to trigger Python and saving down xlsx file

I am trying to save the .xlsx file and using VBA as a wrapper to execute the python file. However, I can validate that python code runs, but somehow .xlsx file is not saved. When I run the same python file via IDE, it saves down the .xlsx file.
VBA code
Sub RunPython()
Dim shell As Object
Dim exepath, scriptPath As String
Set Shell = VBA.CreateObject("Wscript.Shell")
exePath = """C:\Program Files\...\python.exe"""
scriptPath = "C:\....\mymodule.py"
Python Script
import pandas as pd
import xlsxwriter
df = pd.DataFrame(np.random.randn(5,2),index=range(0,10,2),columns =list('AB'))
excel_file ='sample.xlsx'
writer = pd.ExcelWriter(excel_file,engine='xlsxwriter')
df.to_excel(writer,sheet_name='Data')
print ("file read")
writer.save()
writer.close()
Does that 'excel_file' have a path?
Does Python use a current directory and automatically add it to Excel file name?
If yes, do you know how to obtain it and can you look for .xlsx file there?
If not, how do you check if the .xlsx file has been saved? Where are you looking for?
Does Python raise any error?
I am looking to the code mostly like a VBA user...
I would suggest to send a message from Python, containing the current directory path. Supposing that the .xlsx workbook path has not somehow been defined and the code presented here does not include that part. Theoretically it should use the same current directory, but I think it is good to be checked...

Running .exe using VBA

So I created an .exe file (tlsolver.exe) to run using VBA (TLSolver.xlsm). When I launch the .exe, it runs some calculations, spits out a csv file, and then I use VBA to copy that data onto my excel sheet.
This is the VBA code I am using:
Public Sub StartExeWithArgument()
Dim strProgramName As String
ActiveWorkbook.Save
strProgramName = "C:\Users\My.Name\Desktop\Python\Tagless\tlsolver.exe"
Call Shell("""" & strProgramName & """", vbNormalFocus)
End Sub
When I run the macro, the console window pops up as it should and then quickly closes. I managed to see this error before it closes:
IOError: [Errno 2] No such file or directory: 'TLSolver.xlsm'
I know that the .exe works perfectly fine when I doubleclick on the file regularly, so I am inclined to think that I am messing up something silly in the VBA.
Any help appreciated!
Edit: I know the sub is labeled as StartExeWithArgument, but there is no argument required, simply click and run.
The shell command is executing correctly. The exe launches and then looks for the .xlsm file in the current path. What is happening is that it is not able to find the TLSolver.xlsm in the current directory and hence the error IOError: [Errno 2] No such file or directory: 'TLSolver.xlsm'
Three suggestions in such a case.
Change the directory in VBA using ChDir to the directory where the excel file resides and then launch the exe OR
Place both files in the same directory. OR
Rewrite the python exe code (This falls out of my expertise so can't help you here) to prompt the user to select the excel file.
VBA PART (Suggestion 1)
Public Sub StartExeWithArgument()
Dim strProgramName As String
Dim xlFilePath As String
'~~> Path of the excel file. Change as applicable
xlFilePath = "C:\Temp"
ActiveWorkbook.Save
'~~> Change directory
ChDir xlFilePath
strProgramName = "C:\Users\My.Name\Desktop\Python\Tagless\tlsolver.exe"
Call Shell("""" & strProgramName & """", vbNormalFocus)
End Sub

Categories

Resources