excel 如何使Python代码与VBA一起运行

iecba09b  于 2023-04-13  发布在  Python
关注(0)|答案(1)|浏览(105)

我没有任何VBA的经验,所以我有点挣扎。
所以我有这个Python代码,它进行API身份验证,然后将API调用的JSON转换为Excel文件并保存它。

Sub RunPythonScriptQuery()

Dim objShell As Object
Dim PythonExePath As String, PythonScriptPath As String
ActiveWorkbook.Save
ChDir ActiveWorkbook.Path

    Set objShell = VBA.CreateObject("Wscript.Shell")
    
    PythonExePath = """C:\Users\me\AppData\Local\Programs\Python\Python39\python.exe"""
    PythonScriptPath = """C:\Users\me\vbatest\parse.py"""
    
    objShell.Run PythonExePath & PythonScriptPath
    
    MsgBox ("File parsed!")
    
End Sub

我想做的是点击Excel上的一个按钮并执行整个操作.即使我没有得到任何错误,它不是保存文件,因为我需要.你有任何线索,我如何解决这个问题与VBA?

nwsw7zdq

nwsw7zdq1#

这个代码为我工作。
在Excel VBA中-

Option Explicit

Sub sbRunPythonScriptHello()
Dim objShell As Object
Dim PythonExePath As String
Dim PythonScriptPath As String
    Set objShell = VBA.CreateObject("Wscript.Shell")
    PythonExePath = """C:\Users\david\AppData\Local\Programs\Python\Python311\python.exe"""
    PythonScriptPath = """C:\Users\david\Desktop\py_HelloWorld.py"""
    objShell.Run PythonExePath & PythonScriptPath
    MsgBox ("Hello World Python from VBA")
End Sub

下面是VBA调用的Python代码
来自-digitalocean.com/community/tutorials/python-wait-time-wait-for-input

import time
sec = input('Let us wait for user input. Let me know how many seconds to sleep now.\n')
print('Going to sleep for', sec, 'seconds.')
time.sleep(int(sec))
print('Enough of sleeping, I quit!')
time.sleep(int(sec))

这是使用Windows 11 -

  • 版本Windows 11家庭版22 H2安装在20/01/2023 OS build 22621.1413*

Excel -

  • Microsoft® Excel® for Microsoft 365 MSO(版本2303内部版本16.0.16227.20202)64位 *

关于Python -

  • Python 3.11.2(tags/v3.11.2:878ead1,Feb 7 2023,16:38:35)[MSC v.1934 64 bit(AMD64)] on win32*

相关问题