场景::我有一个简单的VBA代码,应运行python脚本。
问题:由于某种原因,此代码(是我在这里找到的How to call python script on excel vba?的直接变体)似乎不起作用。它可以完全运行VBA部分,但不执行python脚本的任何功能。
VBA代码:
'TGCAGCAT|TCTATCTATCTA|GCTAAGCC'
Python代码:
Option Explicit
Sub Macro1()
Dim args As String
Dim Ret_Val
args = "\\Network\structured\Uploader_v2.py"
Ret_Val = Shell("C:\Users\DGMS\AppData\Local\Continuum\anaconda2\python.exe" & " " & args, vbNormalFocus)
End Sub
obs :我的python代码基本上从用户(文件对话框)获取一些路径输入,然后获取一些数据并保存到另一个文件。
问题::考虑到python代码在单独运行时可以正常工作,为什么不能从excel中正确运行它是什么原因?有办法解决这个问题吗?
答案 0 :(得分:3)
我的使用方式:
Shell "cmd.exe /S /c " & "C:\somePath\Uploader_v2.py"
这是一些我之前构建的代码示例:
Option Explicit
Sub TestMe()
Dim path As String: path = "C:\Python\"
Dim pathExe As String
Dim i As Long
Dim txtStream As TextStream 'Library - Microsoft Scripting Runtime
Dim fso As New FileSystemObject 'Library - Microsoft Scripting Runtime
Dim fileName As String
Columns("C:D").Clear
For i = 1 To 8
fileName = "file" & i & ".txt"
pathExe = path & "CodeForces.py" & " """ & Cells(i, 1) & """ >" & path & fileName
Shell "cmd.exe /S /c " & pathExe
Application.Wait Now + #12:00:01 AM#
Set txtStream = fso.OpenTextFile(path & fileName)
Cells(i, 3) = txtStream.ReadLine
txtStream.Close
'Kill path & fileName
If Cells(i, 3) = Cells(i, 2) Then Cells(i, 4) = "Pass..."
Next i
End Sub
它在C:\Python\CodeForces.py
中运行Python exe,并将其结果导出到记事本中。