简体   繁体   中英

Run python script stored in excel cell

I have excel workbook and in a sheet in range("A1"), suppose I have this line into the cell

print('Hello World')

Is there a way to run this python script from the cell from VBA itself?

Thanks a lot @Anu

Sub Test()
    Dim PID
    PID = Shell("python -c '" & Range("A1").Value & "'", vbNormalNoFocus)
End Sub

How can I print the output to the immediate window in VBE?

I tried to put a python script in a cell but this doesn't give me the correct output (No errors appeared but the images are not converted to Photos/New folder

import os
from PIL import Image

dirname_read = r"C:/Users/Future/Desktop/Photos/Demo/"
dirname_write = r"C:/Users/Future/Desktop/Photos/New/"
names = os.listdir(dirname_read)
count = 0

for name in names:
    img=Image.open(dirname_read+name)
    name=name.split(".")
    if name[-1] == "png" or name[-1] == "jpeg" or name[-1] == "PNG":
        name[-1] = "jpg"
        name = str.join(".", name)
        to_save_path = dirname_write + name
        img = img.convert('RGB')
        img.save(to_save_path)
        count+=1     
    else:
        name = str.join(".", name)
        to_save_path = dirname_write + name
        img.save(to_save_path)

images = [file for file in os.listdir(dirname_write) if file.endswith(('jpeg', 'png', 'jpg', 'PNG'))]
for image in images:
    img = Image.open(dirname_write + image)
    img = img.resize((360, 540), Image.ANTIALIAS)
    rgb_img = img.convert('RGB')
    rgb_img.save(dirname_write + image)

print("Total Converted Count: ", count)

Using VBA you should be able to run the python shell. this way you can pass the code into it. python -c 'print(f"test")' the -c flag allows passing of code as a string.

EDIT: the VBA code would looks a lot like this PID = Shell("python -c 'Range("A1").Value'", vbNormalNoFocus) (I'm winging this part since VBA is not my primary language)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM