Setting criteria on autofilter in pyWin32

I can configure the autofilter using pyWin32, but I wondered if the default filter could be set and what the syntax would be.

For example, I would like to set the filter in the year column and set the default value for the current year.

xl = Dispatch("Excel.Application") 
xl.Workbooks.Open(file_path) 
xl.ActiveWorkbook.Worksheets(sheetname).Range("A2:A6").AutoFilter(1)
xl.ActiveWorkbook.Close(SaveChanges=1)

I looked at the pywin32 documentation online as well as the Microsofts website, but cannot figure out how to translate the MS syntax to pywin32

Range("A2:A6").AutoFilter Field:=1, Criteria1:=rng.Value
+3
source share
3 answers

I ran into the same problem, and after several experiments, I found that I could set the range in the attribute Columns. Since I wanted autofilter on columns A through I, I set the following criteria:

xl.ActiveWorkbook.ActiveSheet.Columns("A:I").AutoFilter(1)

. , B thru F, AutoFilter . , :

xl.ActiveWorkbook.ActiveSheet.Columns("B:F").AutoFilter(1)

+3

: http://msdn.microsoft.com/en-us/library/office/bb242013(v=office.12).aspx.

Excel VBA pywin32. , , "2012", , Criteria1 :

MyYearRange.AutoFilter(Field=1, Criteria1="2012")
+1

, , . . xlwings pywin32. xlwings api pywin32, .

import xlwings
#puts the excel window into focus or opens it up. It evens work on csv files.
wb = xlwings.Book('C:\\Users\\yourusername\\Desktop\\Excel.xlsx')

#Choose the sheet you want to focus
datasht = wb.sheets['Sheet1']

#Pay attention to where you the .api. part. It matters if you are trying to achieve something specific. AND MAKE SURE to that you follow case-sensensitive typing for 'Range' and 'Autofilter'.
datasht.api.Range('A1:J10').AutoFilter(3,'SomeFilterValue')

Unfortunately, I'm not sure how to implement the rest of the arguments. You pretty much just have to figure out how to translate arguments in python. I got it to work, but I'm not sure if you have any problems. here is what will work

datasht.api.Range('A1:J10').AutoFilter(3,'filtervalue1',2,'filtervalue1',1)

Read the 2nd link if you need to call the Operator parameter: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-autofilter-method-excel https://msdn.microsoft. com / en-us / vba / excel-vba / articles / xlautofilteroperator-enumeration-excel

0
source

Source: https://habr.com/ru/post/1748385/


All Articles