excel 通过VBA运行Python脚本时出现“错误13权限被拒绝”

oaxa6hgo  于 2023-03-31  发布在  Python
关注(0)|答案(1)|浏览(119)

我正在尝试通过VBA打开的Python脚本对.xlsm文件进行一些数据分析,尽管我已经通过Powershell检查了我的系统是否具有打开它的权限。
感兴趣的Python文件摘录:

import pandas as pd
import csv

df = pd.read_excel('2020 csv prices_less_till_thu called from vba1.xlsm')
df.to_csv('2020 csv prices_less_till_thu called from vba1.csv')

filename = '2020 csv prices_less_till_thu called from vba1.csv'

with open(filename) as csv_file:

知道这可能是权限错误(已经尝试了this的解决方案),我使用PowerShell检查了该文件的访问不受限制:

在运行VBA模块时:

Set objShell = VBA.CreateObject("Wscript.Shell")
    
    PythonExePath = """C:\Users\[REDACTED]\python.exe """
    PythonScriptPath = """C:\Users\[REDACTED]\Price analysis\Check 2020 from VBA.py"""
    
    objShell.Run PythonExePath & PythonScriptPath

出现Errno 13错误:

我已经尝试了上面的修复,添加空间的路径,但似乎不能修复它?
知道吗谢谢!
PS:你知道有什么库可以成为一个一体化的解决方案吗?

kr98yfug

kr98yfug1#

在Excel中创建csv文件。

Option Explicit

Sub demo()
    Const PYEXE = """C:\Users\[REDACTED]\python.exe"" " 
    Const PY = """C:\Users\[REDACTED]\Price analysis\Check 2020 from VBA.py"" "

    Dim csvname As String, folder As String, cmd

    folder = ThisWorkbook.Path & "\"
    csvname = Replace(ThisWorkbook.Name, ".xlsm", ".csv")
    
    ' create csv copy
    ThisWorkbook.Sheets("Sheet1").Copy
    With ActiveWorkbook
        Application.DisplayAlerts = False ' replace existing
        .SaveAs Filename:=folder & csvname, FileFormat:=xlCSV, _
         CreateBackup:=False
        Application.DisplayAlerts = True
        .Close
    End With

    ' run python script with filename as arg 1
    cmd = PYEXE & PY & Chr(34) & folder & csvname & Chr(34)
    Debug.Print cmd
    With VBA.CreateObject("Wscript.Shell")
        .Run cmd
    End With

End Sub

Python脚本

import pandas as pd
import sys, csv

csvname = sys.argv[1]
with open(csvname) as csv_file:
    reader = csv.DictReader(csv_file)
    
    for row in reader:
         continue #print(row)
    
print('Opened ' + csvname + "\nLines read {}".format(reader.line_num))
input("Press return to continue")

相关问题