Sort a Range of Cells, win32com.client

霸气de小男生 提交于 2019-12-23 02:36:23

问题


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

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:

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.

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?


回答1:


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                                 


来源:https://stackoverflow.com/questions/34247373/sort-a-range-of-cells-win32com-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!