在VBA中调用python代码:权限错误权限、错误、代码、VBA

2023-09-03 15:01:03 作者:就这样再见

我正在尝试从VBA(run_report.xlsm)运行python代码。

我的xlsm文件和所有的py文件都在同一个目录中。

Python操作Excel的Xlwings教程 八 Excel使用VBA调用Python

Python代码必须处理run_report.xlsm文件中本身的数据(同样,这也是我从中运行VBA代码以调用Python脚本的文件)。

这是VBA代码:

Option Explicit
Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript, cmd As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

'Provide file path to Python.exe
'USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = """C:Usersgobro7AppDataLocalProgramsPythonPython39python.exe"""
PythonScript = """C:Usersgobro7Digital Wholesale - Documents2. AmazonCustomer Operations_OTC2. Amazon weekly ReportAmazon weekly automationVL.py"""

cmd = PythonExe & PythonScript
Debug.Print cmd

'Run the Python Script
objShell.run cmd, 0, True




MsgBox "Finished"

End Sub

这是查看我如何定义路径和读取文件的python代码的开始。

import pandas as pd
import numpy as np
import os as os



# Get the user
username = os.getlogin()


# search for directory
directory = r'C:/Users/' + username + '/Digital Wholesale - Documents/2. Amazon/Customer Operations_OTC/02. Amazon weekly Report/Amazon weekly automation/'


# reading SAP extract  files from Run_report.xlsm and creating csv from it

df_1 = pd.read_excel(os.path.join(directory,'Run_report.xlsm'), sheet_name= "weekly",header= None)
df_1 = df_1.drop(df_1.columns[[0,1]], axis=1)
df_1.columns = df_1.loc[3].rename(None)
df_1 = df_1.drop(range(5))

df_1.to_csv(directory + '1.csv', index=False, header= True)


#Read CSV of SAP extract

df_weekly=pd.read_csv(os.path.join(directory,'1.csv'), low_memory=False)

VBA代码为我提供了非常快的msgbox,而Python代码没有运行。

我签入了CMD,它给了我一个PermissionError-因为文件是run_report.xlsm没有关闭,但我已经看到,即使它打开了,也可以调用python脚本并在工作簿中做一些工作。不确定我在这里做错了什么。

推荐答案

此行‘cmd=PythonExe&;PythonScrip’生成以下字符串: C:Usersgobro7AppDataLocalProgramsPythonPython39python.exeC:Usersgobro7Digital批发-文档2.亚马逊客户运营_场外交易

 
精彩推荐