Search code examples
pythonexcelwin32comgroup

Group Range of Rows in Excel uisng Python Win32com


I am attempting to group a range of rows in Excel using the win32com python api for Excel Objects. I can't seem to get it to work. My code is as follows:

    excel = win32com.client.gencache.EnsureDispatch("Excel.Application")
    excel.Workbooks.Open(r"pathtomyexcel.xlsx")
    excel.Visible = True
    book = excel.ActiveWorkbook
    sheet = book.Worksheets("Test")
    sheet.Activate()
    
    # trying to get a range of rows using various methods.

    # Using cell ranges
    sheet.Range(sheet.Cells(6, 1),sheet.Cells(15,1)).Group
    # Using row ranges
    sheet.Range(sheet.Rows(6), sheet.Rows(15)).Rows.Group
    # Using the rows range method
    sheet.Rows("6:15").Group

I found this post, but the answer is not clear as noted in the comments. It seems like the group method needs a range object, however my tests above just aren't doing anything. No errors are occurring either.

for reference, I am using python 2.7 and Excel 2010


Solution

  • Provided code tested on Python 3.11 + Excel 365. It should work well on your env.

    # Using cell ranges
    sheet.Range(sheet.Cells(6, 1),sheet.Cells(15,1)).EntireRow.Rows.Group()
    
    # Using row ranges
    sheet.Range(sheet.Rows(1), sheet.Rows(3)).Rows.Group()
    
    # Using the rows range method
    sheet.Rows("20:25").Rows.Group()
    
    # Using A1 reference
    sheet.Range("A40:A45").EntireRow.Rows.Group()