python to excel 路径_通过VBA运行Python脚本并提供活动工作簿的名称和路径?

编辑:这是相同的问题,但我改写了它,所以它更清晰。

但是,没有答案对我有用,我也不知道我在做什么错。问题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")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值