Search code examples
exceltextboxpywin32

Python win32com - Call TextBox by Name?


I am trying in vain to get the name of a TextBox in MS Excel using pywin32, I have tried recording a macro and I get the following tips, but I cannot translate them from VBA to python. In the sample below I select the Textbox and rename it, all I want is to be able to refer to them by name and I figure this gets me close.

ActiveSheet.Shapes.Range(Array("TextBox 2")).Select
Selection.ShapeRange.Name = "TextBox 3"

This is what I have in python so far to this end.

import win32com.client as win32 
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open("C:\\users\\khillstr\\Testing\\Scripts\\Book1.xlsx")
excel.Visible = True

ws = wb.Worksheets

for w in ws:
    print w.Name
    w.Activate
    canvas = w.Shapes
    for shp in canvas:
        if shp.TextFrame.Characters:
            print shp.TextFrame2.TextRange

Solution

  • for shp in canvas:
        print shp.name
    

    Name is a read/write property for textbox shapes. You can get and set the name using that property. Tested in Excel 2010.