Search code examples
pythonsortingrangewin32com

Sort a Range of Cells, win32com.client


I am trying to sort a range of cells in python using win32com:

enter image description here

Code I've been using is:

sheet.Range("A1:B8").Sort(Key1=sheet.Range("B1"), Orientation=constants.xlAscending)

which is working. It sorts the range of cells by the second column:

enter image description here

When I want, is to sort Descending instead of Ascending:

sheet.Range("B8:A1").Sort(Key1=sheet.Range("B1"), Orientation=constants.xlDescending)

but for some weird reason, it switches the data from each column and doesn't sort the values that were initially in the second column.

enter image description here

I've played with a ton of different parameters types sot the sort method here but nothing seems to work. Has anyone have experience with this method and can suggest how I would get the second column sort descending?


Solution

  • Your orientation argument should either be: xlSortColumns = 1 or xlSortRows = 2. See below Python script adjustment. As the Range.Sort Method shows, Order1, Order2, and Order3 takes the xlAscending = 1 or xlDescending = 2 values.

    import win32com.client
    
    wbk = 'C:\\Path\\To\\Workbook.xlsx'
    
    xlApp = win32com.client.Dispatch("Excel.Application")
    xlApp.Workbooks.Open(wbk)
    
    xlAscending = 1
    xlSortColumns = 1    
    xlApp.Sheets(1).Columns("A:B").Sort(Key1=xlApp.Sheets(1).Range("B1"),
                                        Order1=xlAscending, Orientation=xlSortColumns)
    
    xlApp.Quit
    xlApp = None