Search code examples
pythonexcelvbawin32com

Python win32com VBA UserForm object Caption property set


I am trying to create Excel VBA UserForm using Win32com in Python. I am able to add the UserForm to a workbook, I can even add controls to this form, however I am stuck with updating the properties of the UserForm object itself. For example: I can read the Caption property using the below code, but I had no luck setting it. Does anyone know how to set VBA UserForm properties in Python using win32com?

My Code:

import win32com.client as win32

com_object = win32.gencache.EnsureDispatch('Excel.Application')
xlFile = com_object.Workbooks.Open(Filename = 'MyExcelFileaPath.xlsx')
xlForm = xlFile.VBProject.VBComponents.Add(3) 
print (xlForm.Properties('Caption')) #this works
xlForm.Properties('Caption') = 'Custom Caption' #this does not work - error: SyntaxError: can't assign to function call
xlForm.Properties.Caption = 'Custom Caption' #this does not work

Solution

  • Finally, after a week of research, trial and error I came up with a way to set UserForm object's properties. As I suspected, the answer is kind of silly:

    xlForm.Properties('Caption').Value = 'Custom Caption'
    

    Hope this helps someone to save some time.