[Python] Running an SQL query through python from VBA

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create SQL query within excel, load this through VBA into a python script, run the sql through a python to produce the data, and copy the values back into the excel document. The python code works and accepts the query as sys.argv[1], but when I run the following script, the cmd box comes up, and then immediately closes. I have put time.sleep(10) within the python script to determine if it is a python issue but believe it to be a VBA. Any suggestions?

    Public Function LoadSQLFromCell(cellReference As String, sheetReference As String, outputCell As String, outputSheet As String)
    Dim conn As Object
    Dim rs As Object
    Dim sqlQuery As String
    Dim ws As Worksheet
    Dim cell As Range
    Dim objShell As Object
    Dim PythonExePath As String
    Dim PythonScriptPath As String

    ' Set the worksheet where the SQL query is stored
    Set ws = ThisWorkbook.Sheets(sheetReference)

    ' Get the cell reference
    Set cell = ws.Range(cellReference)

    ' Read the SQL query from the specified cell
    sqlQuery = cell.Value


    ' Escape double quotes in the SQL query
    sqlQuery = Replace(sqlQuery, """", """""")

    ' Set the paths for Python executable and script
    PythonExePath = """C:\Program Files\Python39\python.exe"""
    PythonScriptPath = """C:\Program Files\localData\updater_sysinput.py"""


    ' Create a new Wscript.Shell object

    queryString = PythonExePath & " " & PythonScriptPath & " """ & sqlQuery & """"
    MsgBox queryString

    ' Run the Python script with the SQL query as input
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run queryString, 1, True

    ' Set the worksheet where the output will be pasted
    Set ws = ThisWorkbook.Sheets(outputSheet)
    ws.Range(outputCell).Select
    ws.Paste
    End Function

    Continue reading...

Compartilhe esta Página