Search code examples
pythonvbashellpathexport-to-csv

Running Python code by calling it with VBA code


I cannot get this Python code to run by calling it with a VBA macro.

The Python code which writes a CSV to my desktop.

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

I attempt to call this code with VBA code in Excel.

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

A black box command prompt box flashes on the screen but the CSV does not write.


Solution

  • The problem here was two fold. First I was not importing numpy in my python script. Second I did not have my path set up correctly. A great and up to date video on how to do this is linked below.

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