简体   繁体   English

Excel VBA 2016 中 Range.Autofilter 的运行时错误 1004

[英]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:-这在 Excel 2010 中工作正常,但在 Excel 2016 中我得到:-

Run-time error '1004' AutoFilter method of Range class failed Range 类的运行时错误“1004”自动筛选方法失败

Also, I can manually click the filter icon in the Ribbon (Under Data > Filter) but cannot do this with VBA code此外,我可以手动单击功能区中的过滤器图标(在数据 > 过滤器下),但不能使用 VBA 代码执行此操作

Any ideas much appreciated.任何想法都非常感谢。

The AutoFilter gives 1004 error, when you are trying to filter by an empty row.当您尝试按空行进行过滤时,自动AutoFilter会出现1004错误。 Try to put something on row 23 and to filter it again like this:尝试在第23行放一些东西并像这样再次过滤它:

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.如果它有效,那么您在第 23 行中根本没有值,因此它无法应用自动过滤器。


In general, the AutoFilter in Excel has some strange behaviour.通常,Excel 中的AutoFilter有一些奇怪的行为。 Eg, if you open a new Excel file and you run the following code:例如,如果您打开一个新的 Excel 文件并运行以下代码:

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.它会给你1004错误。 Let's call this time momentum FirstTime .让我们称这个时间势头为FirstTime

Then, if you uncomment the two ranges and run it, the AutoFilter would appear.然后,如果您取消对这两个范围的注释并运行它,则会出现AutoFilter

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 .现在奇怪的部分 - 从工作表中删除所有单元格,对这两个范围进行评论,它看起来真的像它在FirstTime时的样子 But if you run the code it will put an AutoFilter on the empty 23rd row without a problem.但是,如果您运行该代码,它将毫无问题地在空的第 23 行上放置一个自动过滤器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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