I have a Python script to interact with a database and give some result. I create a new sheet in a workbook and save this result.
I have a workbook and I want to call this script from all the cells in a particular row in the active sheet of the workbook using the cell value as an argument to the script.
I came to know the following things
1) Create a VBA macro and call a script from the macro
2) Insert the macro in the sheet
I have zero knowledge about VBA and was not able to find good resources for it.
Can my problem can be solved using Python itself?
Can I call a Python script from some cells in a workbook using cell values as an argument to the script?
Your question is too broad. The answer is yes. There are several libraries for it. Look into openpyxl
, win32com
: also called pywin32
, and pandas
Of these 3,
openpyxl
is the easiest to use but might not contain the full functionality of Excel VBA.
win32com
is the closest to VBA and most function calls are the same right down to the way arguments are passed into them.
pandas
is the right choice if you're crunching a lot of numbers and mainly using the spreadsheet files as data storage.
EDIT:
Screenshot of Excel UI with Command Button:
VBA Code:
Public Sub StartExeWithArguments()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets("Config") 'Have a sheet named "Config"
'The values here are for passing in the args to a python script that runs as an .exe file
strProgramName = Trim(ws.Range("B4").Value) '.exe filepath
strPdfLoc = Trim(ws.Range("B5").Value) 'file being acted on
strPdfSave = Trim(ws.Range("B6").Value) 'file being created
strPdfPass = Trim(ws.Range("B7").Value) 'additional argument
'string concatenation
strArgument = strPdfLoc & " " & strPdfSave & " " & strPdfPass
'Checking the cmd line to be passed into the Shell as args for the .exe
Debug.Print """" & strProgramName & """ " & strArgument & """"
'How VBA calls the cmd to run
'Note that """" actually prints one " because " is an escape char and also a string quote in VBA
Call Shell("""" & strProgramName & """ " & strArgument & """", vbNormalFocus)
End Sub
The above code showcases how you can create a macro to run an .exe and pass in arguments.
As for trigger on cell selection , use the example showcased in this link .
In order to create an .exe
file, use pip3 install pyinstaller
and cd
your way to the folder containing the .py
script, then run pyinstaller --onefile yourscript.py
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.