Python Input Text into The Next Empty Cell of an Excel Sheet Column for Multiple Workbooks

Question:

I have 30 workbooks with naming convention (myfile1.xlsm, myfile2.xlsm, myfile3.xlsm etc) I would like to input a text into the next empty cell of a specific column(Q) of a specific worksheet(sheet1) for all 30 workbooks. The code below works perfect for one workbook but I need to do same thing for all 30 workbooks so I am trying to put it in a python def function, how do I put the code below in a def function so I can apply it to all 30 files at the same time?

import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.cell import Cell

wb = openpyxl.load_workbook('C:/Users/me/randomfolder/myfile1.xlsm',  keep_vba=True)
ws = wb["Sheet1"]

#insert text in the first empty cell in column Q starting from cell Q5
for row in ws['Q5:Q1000']:
cell = row[0]
if cell.value is None:
    cell.value = 'random text'
    break

#save file
wb.save(r'C:/Users/me/randomfolder/myfile1.xlsm')
Asked By: ohmandy

||

Answers:

If your .xlsm files are located in the same directory (in your case, "C:/Users/me/randomfolder"), you can then use Path.glob to return their paths and pass them as a parameter of openpyxl.load_workbook one by one in a for loop.

Try this :

from pathlib import Path
import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.cell import Cell


files_directory = "C:/Users/me/randomfolder"

for file in Path(files_directory).glob(".xlsm"):
    
    wb = openpyxl.load_workbook(file,  keep_vba=True)
    ws = wb["Sheet1"]

    #insert text in the first empty cell in column Q starting from cell Q5
    for row in ws['Q5:Q1000']:
    cell = row[0]
    if cell.value is None:
        cell.value = 'random text'
        break

    #save file
    wb.save(file)
Answered By: abokey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.