excel - 使用网络路径从 vba 运行 Python 脚本

标签 excel vba

场景:我有一个简单的 VBA 代码,应该运行 python 脚本。

问题:由于某种原因,此代码(这是我在此处找到的代码的直接变体: How to call python script on excel vba? )似乎不起作用。它运行 VBA 部分直至完成,但不执行 python 脚本的任何功能。

VBA代码:

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

Python 代码:

import pandas as pd
import datetime
import os
import Tkinter
from Tkinter import Tk
from tkFileDialog import askdirectory
from Tkinter import filedialog
from os import listdir
from os.path import isfile, join
import glob

# Get input and output paths
Tk().withdraw() 
sourcefolder =  askdirectory()
outputfolder = askdirectory()
selectmonth = raw_input("Please enter month ('January', 'February'...:")

# Get content
all_files = glob.glob(os.path.join(sourcefolder, "*.xls*"))
contentdataframes = []
contentdataframes2 = []

for f in all_files:
    df = pd.read_excel(f)
    df['Name'] = os.path.basename(f).split('.')[0].split('_')[0]
    mask = df.columns.str.contains('Base')
    c2 = df.columns[~mask].tolist()
    df = df[c2]
    contentdataframes.append(df)

concatenatedfinal = pd.concat(contentdataframes)

concatenatedfinal .to_excel(outputfolder + "/" + selectmonth + "_Upload.xlsx",index=False)

观察:我的Python代码基本上从用户(filedialog)获取一些路径输入,然后获取一些数据并保存到另一个文件。

问题:考虑到Python代码在单独运行时可以工作,那么它不能从Excel正常运行的原因可能是什么?有办法解决这个问题吗?

最佳答案

我使用的方式:

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,并将结果导出到记事本。

关于excel - 使用网络路径从 vba 运行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51280760/

相关文章:

excel - SAS 和 Excel 中百分位数的不同结果

python - 在 python (xlwt) 中设置 excel 列样式

excel - 根据相邻的下拉值更改 Excel 中的单元格颜色

database - Power Query 日期格式

excel - VBA 嵌套错误 GoTo

Excel VBA - 使用形状作为切换按钮

vba - 按地址从给定范围中选择列

vba - Excel VBA设置命名单元格公式使用范围属性

api - 将 URL 内容直接下载为字符串 (VB6),无需保存到磁盘

vba - 如何从 PowerPoint 调色板中获取 RGB/Long 值