简体   繁体   中英

Run-time error 1004 with Range.Autofilter in Excel VBA 2016

My code is

With ActiveSheet
   .AutoFilterMode = False
   .Range("23:23").AutoFilter
End With

This works fine in Excel 2010 , but with Excel 2016 I get:-

Run-time error '1004' AutoFilter method of Range class failed

Also, I can manually click the filter icon in the Ribbon (Under Data > Filter) but cannot do this with VBA code

Any ideas much appreciated.

The AutoFilter gives 1004 error, when you are trying to filter by an empty row. Try to put something on row 23 and to filter it again like this:

Public Sub TestMe()    
    With ActiveSheet
       .AutoFilterMode = False
       .Range("23:23").Cells(1) = 1
       .Range("23:23").Cells(2) = 2
       .Range("23:23").AutoFilter
    End With

End Sub

If it works, then you simply do not have values in row 23, thus it cannot apply an autofilter.


In general, the AutoFilter in Excel has some strange behaviour. Eg, if you open a new Excel file and you run the following code:

Public Sub TestMe()

    With ActiveSheet
       .AutoFilterMode = False
       '.Range("23:23").Cells(1) = 1
       '.Range("23:23").Cells(2) = 2
       .Range("23:23").AutoFilter
    End With    
End Sub

It will give you the 1004 error. Let's call this time momentum FirstTime .

Then, if you uncomment the two ranges and run it, the AutoFilter would appear.

Now the strange part - delete all cells from the sheet, comment back the two ranges and it really looks like the way it was, at the FirstTime . But if you run the code it will put an AutoFilter on the empty 23rd row without a problem.

删除现有文件管理器并再次运行

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM