2015-12-13 52 views
1

我想排序的单元格区域中使用Python win32com:我一直在使用排序的单元格区域,win32com.client

enter image description here

代码是:

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

这是工作。

enter image description here

当我想,是降序排序,而不是递增:

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

但出于某种奇怪的原因,它切换数据它通过第二列排序的单元格区域每列,并不排序最初在第二列中的值。

enter image description here

我一吨的不同参数的发挥SOT类型的排序方法here但似乎没有任何工作。有没有人有这种方法的经验,并可以建议如何得到第二列降序?

回答

2

您的方向参数应为:xlSortColumns = 1xlSortRows = 2。请参阅下面的Python脚本调整。作为Range.Sort Method所示,Order1Order2,和Order3xlAscending = 1xlDescending = 2值。

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         
+0

这是很棒的Parfait。这基本上让我想要什么,只有一个例外。我需要一个单元格范围,而不是整列,所以采取你的建议,而不是xl.App.Columns(“A:B”),我用xlApp.Range(“A1:G9”)代替 – Mike

相关问题