【问题标题】:How to execute Python script through excel VBA如何通过excel VBA执行Python脚本
【发布时间】:2019-06-13 01:05:00
【问题描述】:

我正在尝试通过 Excel VBA 运行 Python 脚本

我尝试了以下代码,但没有任何反应:

这是 VBA 代码:

RetVal = Shell("C:\Program Files\Python37\python.exe C:\Users\kailung\Desktop\kai\VBA\june_Longchen\test\VBA.py")

我的 python 脚本只是重命名文件夹中的文件(我在 Python IDLE 中测试过,没问题):

import os, sys

dir_path = os.path.dirname(os.path.realpath(__file__))

# Open a file
dirs = os.listdir(dir_path)

i=1

# This would print all the files and directories
for file in dirs:
   if file!='VBA.xlsm' and file!='VBA.py' and file!='~$VBA.xlsm':
        print(file) #print all the files
        i=str(i) #change to string for file name
        i=i + '.xls' #add extension
        os.rename(file,i) #rename the file
        size=len(i) 
        i=i[0:size-4] #remove the extension
        i=int(i) #change back to numerical
        i=i+1 #new numerical name

【问题讨论】:

  • 通常情况下,您希望在任何带有空格的路径周围加上引号(并且总是引用路径并没有什么坏处)RetVal = Shell("""C:\Program Files\Python37\python.exe"" ""C:\Users\kailung\Desktop\kai\VBA\june_Longchen\test\VBA.py""")
  • 还是不行:C
  • 不是 Python 人,但 reddit.com/r/learnpython/comments/8cy9k9/… 看起来很相关

标签: python excel vba


【解决方案1】:

使用 pyinstaller 将您的 .py 文件转换为 .exe 文件,并直接从 VBA 代码运行 .exe 程序。

How to use pyinstaller?

【讨论】:

  • 我已经使用了以下代码,但它仍然没有给我任何东西,RetVal = Shell("C:\Users\kailung\Desktop\kai\VBA\june_Longchen\test\VBA.exe", 1)
  • 提示说正在修改C:\Users\kailung\Documents中的文件,这不是正确的目录。 :C
  • 我发现了问题,所以基本上我必须在 VBA 中更改我的目录: ChDir "C:\Users\kailung\Desktop\kai\VBA\june_Longchen\test" RetVal = Shell("C: \Users\kailung\Desktop\kai\VBA\june_Longchen\test\VBA.exe", 1)
猜你喜欢
  • 1970-01-01
  • 2018-12-19
  • 2015-11-23
  • 2013-04-17
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
相关资源
最近更新 更多