首页 > 解决方案 > 通过使用 VBA 代码调用 Python 代码来运行它

问题描述

我无法通过使用 VBA 宏调用此 Python 代码来运行它。

将 CSV 写入我的桌面的 Python 代码。

import pandas as pd
string=['hello world','Sup']
DFstring=pd.DataFrame(string)
DFstring.to_csv("C:/Users/Peter_K/Desktop/test.csv")

我尝试在 Excel 中使用 VBA 代码调用此代码。

Sub xls2py()
    Dim objShell As Object
    Dim PythonExe, PythonScript As String
    ChDir ActiveWorkbook.Path

    Set objShell = VBA.CreateObject("Wscript.Shell")

    PythonExe = """C:\Users\Peter_K\anaconda3\python.exe"""
    PythonScript = "C:\Users\Peter_K\Desktop\Untitled3.py"

    objShell.Run PythonExe & PythonScript
    Set objShell = Nothing

End Sub

黑框命令提示框在屏幕上闪烁,但 CSV 不写入。

标签: pythonvbashellpathexport-to-csv

解决方案


这里的问题有两个方面。首先,我没有在我的 python 脚本中导入 numpy。其次,我的路径设置不正确。下面链接了有关如何执行此操作的精彩且最新的视频。

https://www.youtube.com/watch?v=uOwCiZKj2rg&t=510s


推荐阅读