Reading and writing to an Excel ActiveX textbox with Python can be fun. If you really do not have anything better to do. Anyway, if this is your current task, you are on the correct place to see how it is done.
Imagine having two textboxes in Excel file named xl.xlsx
which is present in the same directory as the python code, looking like this:
The left one is named TextBox2
and the right one is named TextBox1
. Then, the idea is to print the text of the right one on the console and to be able to write some text on the left one. Long story short, the code is self-explanatory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import os import xlwings as xw def print_text_box(): current_dir = os.path.dirname(os.path.realpath(__file__)) wb_path = f"{current_dir}\\xl.xlsx" sheet_name = 'Main' wb = xw.Book(wb_path) sht = wb.sheets[sheet_name] my_text = sht.api.OLEObjects("TextBox1").Object.Value print(my_text) def write_into_text_box(text_to_write, label_name): current_dir = os.path.dirname(os.path.realpath(__file__)) wb_path = f"{current_dir}\\xl.xlsx" wb = xw.Book(wb_path) wb.sheets('Main').api.OLEObjects(label_name).Object.Value = text_to_write if __name__ == '__main__': print_text_box() write_into_text_box("VitoshAcademy.com will be on textbox 2!", "TextBox2") |
The code can be probably improved in a lot of ways, putting the workbooks and the texts as parameters and passing them to the functions, but this is not the idea of the article! Enjoy! 🙂