excel vba 多条件查询,VBA代码实现查询功能怎么编写?

使用excel vba筛选出多个条件
我在A,1、2、3、4、5列和A,B,C中有8个变量。我的目的是过滤掉A,B,C并仅显示1-5。我可以使用以下代码执行此操作:My_Range.AutoFilter Field:=1, Criteria1:=Array("1", "2", "3","4","5"), Operator:=xlFilterValues但是代码的作用是过滤变量1到5并显示它们。我不会做相反的事情,但是通过滤除A,B,C并显示变量1至5会产生相同的结果我尝试了这段代码:My_Range.AutoFilter Field:=1, Criteria1:=Array("<>A", "<>B", "<>C"), Operator:=xlFilterValues但这没有用。为什么我不能使用此代码?它给出了这个错误:运行时错误1004范围类的自动筛选方法失败我该如何执行呢?
3回答
江户川乱折腾
我认为(通过试验-MSDN在这里无济于事)没有直接的方法可以做到这一点。设置Criteria1为an Array等效于使用下拉菜单中的复选框-就像您说的那样,它只会根据与数组中的一项相匹配的项目来过滤列表。有趣的是,如果您具有文字值,"<>A"并且"<>B"在这些列表和过滤器上,宏记录器将提供Range.AutoFilter Field:=1, Criteria1:="=<>A", Operator:=xlOr, Criteria2:="=<>B"哪个有效。但是,如果您同时也具有文字值"<>C",并且在记录宏时对所有三个值进行了过滤(使用复选框),则宏记录器会精确地复制您的代码,然后该代码将失败并显示错误。我想我会把它称为一个错误-使用UI可以执行某些过滤器,而使用VBA则不能。无论如何,回到您的问题。可以过滤不等于某些条件的值,但最多可以过滤两个不适合您的值:Range("$A$1:$A$9").AutoFilter Field:=1, Criteria1:="<>A", Criteria2:="<>B", Operator:=xlAnd根据确切的问题,有几种解决方法:将“帮助列”与B列中的公式一起使用,然后对其进行过滤-例如,=ISNUMBER(A2)或=NOT(A2="A", A2="B", A2="C")随后对TRUE如果您无法添加列,请使用具有Criteria1:=">-65535"(或比您期望的数字低的合适数字)的自动过滤器,该过滤器会过滤掉非数字值-假设这是您想要的编写一个VBA子来隐藏行(与自动过滤器不完全相同,但根据您的需要可能就足够了)。例如:Public Sub hideABCRows(rangeToFilter As Range)&nbsp; Dim oCurrentCell As Range&nbsp; On Error GoTo errHandler&nbsp; Application.ScreenUpdating = False&nbsp; For Each oCurrentCell In rangeToFilter.Cells&nbsp; &nbsp; If oCurrentCell.Value = "A" Or oCurrentCell.Value = "B" Or oCurrentCell.Value = "C" Then&nbsp; &nbsp; &nbsp; oCurrentCell.EntireRow.Hidden = True&nbsp; &nbsp; End If&nbsp; Next oCurrentCell&nbsp; Application.ScreenUpdating = True&nbsp; Exit SuberrHandler:&nbsp; &nbsp; Application.ScreenUpdating = TrueEnd Sub
幕布斯7119047
使用自动筛选的选项Option ExplicitPublic Sub FilterOutMultiple()&nbsp; &nbsp; Dim ws As Worksheet, filterOut As Variant, toHide As Range&nbsp; &nbsp; Set ws = ActiveSheet&nbsp; &nbsp; If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then Exit Sub 'Empty sheet&nbsp; &nbsp; filterOut = Split("A B C D E F G")&nbsp; &nbsp; Application.ScreenUpdating = False&nbsp; &nbsp; With ws.UsedRange.Columns("A")&nbsp; &nbsp; &nbsp; &nbsp; If ws.FilterMode Then .AutoFilter&nbsp; &nbsp; &nbsp; &nbsp;.AutoFilter Field:=1, Criteria1:=filterOut, Operator:=xlFilterValues&nbsp; &nbsp; &nbsp; &nbsp; With .SpecialCells(xlCellTypeVisible)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; If .CountLarge > 1 Then Set toHide = .Cells 'Remember unwanted (A, B, and C)&nbsp; &nbsp; &nbsp; &nbsp; End With&nbsp; &nbsp; &nbsp; &nbsp;.AutoFilter&nbsp; &nbsp; &nbsp; &nbsp; If Not toHide Is Nothing Then&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; toHide.Rows.Hidden = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Hide unwanted (A, B, and C)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Cells(1).Rows.Hidden = False&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Unhide header&nbsp; &nbsp; &nbsp; &nbsp; End If&nbsp; &nbsp; End With&nbsp; &nbsp; Application.ScreenUpdating = TrueEnd Sub
打开App,查看更多内容

我要回帖

更多关于 VBA代码实现查询功能 的文章

 

随机推荐