编辑:这是相同的问题,但我改写了它,所以它更清晰。
但是,没有答案对我有用,我也不知道我在做什么错。问题1:我想从VBA excel运行pythonscript。excel文件没有家(可以在任何桌面上)。我(想要)使用的代码:
Dim Ret_Val
Ret_Val = Shell("C:\python27\python.exe \\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py")
pythonfile在服务器上始终具有相同的路径。我看不到wat在这里错了吗?我得到的只是一个黑色的python屏幕。
在python文件中,我称为工作簿和正确的工作表:
book = xlrd.open_workbook("//10.31.13.22/SharedDocs/3 - Technical/1 - Projects/0 - Internal/RPA 138 - Engineering software/testchipdescription/upload to database/testchipdescription-template-10-11.xltm")
sheet = book.sheet_by_name("Database")
目前,excel工作簿路径已用python硬编码。这将使我回到问题2:我可以以某种方式将excel工作簿的名称和路径传递给pythonscript吗?
编辑:
我在命令提示符下尝试了shell()代码。与VBA中的相同:
"C:\python27\python.exe \\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py"
没用'该系统找不到指定的路径'。
我尝试了这个:
C:\python27\python.exe "\\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py"
而且有效!因此,cmd需要使用“”来处理路径中的空格。但是我不能在VBA中添加它们,因为我不能放置2“”,否则会出错。
解决方案
是的,我找到了问题1的解决方案:
Dim excelToPython As String
excelToPython = """C:\python27\python.exe"" ""\\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py"""
Debug.Print excelToPython
Call Shell(excelToPython)
编辑:
最后,我找到了解决问题2的方法。我仍然没有真正的解决方案,可以使用shell命令将活动工作簿的名称和路径提供给我的python脚本。
但是我将活动工作簿的路径和名称写在与python脚本相同的文件夹中的txt文件中。然后,我通过pythonscript等获取了此信息。好吧,它可以满足我的要求,但这不是一个干净的解决方案。如果有人知道正确的解决方案,请随时分享:o)
我的解决方法:
vba-excel中的代码:
'via pythonscript'
Dim excelToPython As String
Dim myFileTxt As String
Dim fileTxtPath As String
'first give the name and path of active workbook to a txtfile in the same folder as ThemeColor pythonscript'
fileTxtPath = "\\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\actWBdb.txt"
myFile = FreeFile
Open fileTxtPath For Output As myFile
nameWB = ActiveWorkbook.name
pathWB = ActiveWorkbook.path
Print #myFile, nameWB
Print #myFile, pathWB
Close myFile
'run the python file'
excelToPython = """C:\python27\python.exe"" ""\\10.31.13.22\SharedDocs\3 - Technical\13 - Reports & Templates\13 - Description\DescriptionToDatabase.py"""
Call Shell(excelToPython)
python中的代码:
filepath ='//10.31.13.22/SharedDocs/3 - Technical/13 - Reports & Templates/13 - Description/actWBdb.txt'
lines = open(filepath).read().splitlines()
nameWorkbook = lines[0]
pathWorkbook = lines[1]
book = xlrd.open_workbook(pathWorkbook + '/' + nameWorkbook)
sheet = book.sheet_by_name("Database")