我有一个Python脚本可以与数据库交互并给出一些结果。我在工作簿中创建一个新工作表,然后保存该结果。
我有一个工作簿,我想使用该单元格的值作为脚本的参数,从工作簿活动表的特定行中所有单元格中调用此脚本。
我开始了解以下内容
1)创建一个VBA宏并从该宏中调用脚本
2)将宏插入工作表中
我对VBA的知识为零,无法为其找到良好的资源。
我的问题可以使用Python本身解决吗?
我可以使用单元格值作为脚本的参数从工作簿的某些单元格中调用Python脚本吗?
答案 0 :(得分:0)
您的问题太广泛了。答案是肯定的。它有几个库。查看openpyxl
,win32com
:也称为pywin32
和pandas
在这3个中,
openpyxl
是最容易使用的,但可能不包含Excel VBA的全部功能。
win32com
最接近VBA,而且大多数函数调用在参数传递到它们的方式上都是相同的。
如果您要处理大量数字,并且主要使用电子表格文件作为数据存储,那么pandas
是正确的选择。
编辑:
带有命令按钮的Excel UI的屏幕截图:
VBA代码:
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
上面的代码展示了如何创建一个宏来运行.exe并传递参数。
至于触发单元格选择,请使用此link中展示的示例。
为了创建.exe
文件,请使用pip3 install pyinstaller
和cd
进入包含.py
脚本的文件夹,然后运行pyinstaller --onefile yourscript.py
>