1

So, i'm trying to run a Python code using VBA. Read a lot of similar topics here, but could not found an answer.

Every time i use the code below, CMD inform a Permission Error - image below.

The Python script run perfectly on manual click.

Any ideas on the matter?

VBA CODE

Dim obj As Object
Dim PythonExe As String
Dim Script As String

Set obj = VBA.CreateObject("Wscript.Shell")

PythonExe = """C:\Program Files (x86)"""

Script = "C:\Users\User\Documents\testesbulkpdf\firsttry.py"

obj.Run "cmd /k cd /d" & PythonExe & "&& " & "python" & " " & Script

PYTHON CODE

# pip instal PyPDF2

import os

from PyPDF2 import PdfFileMerger


source_dir = os.getcwd()

merger = PdfFileMerger()

for item in os.listdir(source_dir):
    if item.startswith('Doc.'):
        merger.merge(position=0, fileobj=item, bookmark=None, pages=None)
           
    if item.endswith('pdf'):
        merger.append(item)
    
merger.write('try.pdf')
merger.close()



Erro - image and text (https://i.stack.imgur.com/z37a2.jpg)

Traceback (most recent call last):
  File "C:\Users\User\Documents\testesbulkpdf\firsttry.py", line 19, in <module>
    merger.write('try.pdf')
  File "C:\Users\User\AppData\Roaming\Python\Python38\site-packages\PyPDF2\merger.py", line 214, in write
    fileobj = file(fileobj, 'wb')
PermissionError: [Errno 13] Permission denied: 'try.pdf'
  • 1
    you've posted your VBA code twice.... – Tim Williams Aug 02 '20 at 17:27
  • Sorry buddy, edited. – Renan Liporaci Aug 02 '20 at 17:45
  • `getcwd` might be a different directory when the script is called from VBA vs. when you run it directly. – Tim Williams Aug 02 '20 at 17:52
  • **You are right!** I changed getcwd to **os.chdir(r'C:\Users\User\Desktop\Capas geradas automaticamente')** and worked just fine. If you could help me a bit more. Is possible to inform the path using vba? I though something like - import sys, and changing source_dir to source_dir = sys.argv – Renan Liporaci Aug 02 '20 at 18:28
  • You should be able to pass the path as a command line argument to your python script. Eg see https://stackoverflow.com/questions/14393182/passing-python-script-parameter-from-vba – Tim Williams Aug 02 '20 at 20:15
  • @TimWilliams Hi Tim, I think Im having a same problem but cant figure out how to change mine to os.chdir, Could you please take a look on mine ? https://stackoverflow.com/questions/71055354/call-python-code-in-vba-permission-error/71056062#71056062 – Greencolor Feb 09 '22 at 20:19
  • @Greencolor - sorry I'm OK in VBA but no idea about Python – Tim Williams Feb 09 '22 at 20:29

0 Answers0