excel - 有没有办法根据每个单元格内的 10 多个标准进行过滤?
问题描述
我有一个 Excel 表,我需要在其中根据多个条件过滤行。
信息有时位于单元格的中间。
例如,
C12:JFK 2018 年 1 月咖啡
C13:LGA 01/2018 比萨
C14:SFA 意大利面 Mar2017。
我需要根据尽可能多的方式为几百行编写 2018 年 1 月过滤与 2018 年 1 月相关的行。
我尝试了以下方法:
Sub myFilter()
Dim dic As Object
Dim eleData As Variant
Dim eleCrit As Variant
Dim arrData As Variant
Dim vTst As Variant
Set dic = CreateObject("Scripting.Dictionary")
vTst = Array("*Jan 2018*", "*JAN 2018*", "*01/2018*", "*012018*", "*12018*")
With ActiveSheet
.AutoFilterMode = False
arrData = .Range("B1:B" & .Cells(.Row.Count, "B").End(xlUp).Row)
For Each eleCrit In vTst
For Each eleData In arrData
If eleData Like eleCrit Then dic(eleData) = vbNullString
Next
Next
.Columns("B:B").AutoFilter Field:=1, Criteria:=dic.Keys, Operator:=xlFilterValues
End With
End Sub
这段代码给出
运行时错误
“对象不支持此属性或方法”。
如果代码在我的小样本上运行,我会调整代码以适应更大的数据集。
解决方案
Excel 被限制为使用通配符搜索最多 2 个单词,所以也许您正在寻找类似的东西,一个解决该问题的工作
Sub myFilter()
Dim Crit() As Variant
Dim cri() As String
Dim cri2() As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim rng As Range
Crit = Array("Jan 2018", "JAN 2018", "01/2018", "012018", "12018")
Set rng = ActiveSheet.Range("B1:B" & ActiveSheet.Cells(ActiveSheet.Rows.Count, "B").End(xlUp).row) 'HERE Range
ReDim Preserve cri(UBound(Crit))
ReDim Preserve cri2(1)
For i = LBound(Crit) To UBound(Crit)
cri(i) = "=*" & Crit(i) & "*"
rng.AutoFilter Field:=1, Criteria1:=cri(i), Operator:=xlFilterValues 'HERE Field in the Range i.e column Number
j = UBound(cri2)
ReDim Preserve cri2(j + rng.SpecialCells(xlCellTypeVisible).Count)
For Each rw In rng.SpecialCells(xlCellTypeVisible).Rows
cri2(j + 1) = Cells(rw.row, "B").Value 'HERE Column that corresponds to the Filtered Field in this case B
Debug.Print cri2(j + 1)
j = j + 1
Next
Next
rng.AutoFilter Field:=1, Criteria1:=cri2, Operator:=xlFilterValues 'HERE Again Field to Filter On
End Sub
笔记:
- 不需要添加
*
数组,它已经这样做了。 - 取自这里
- 如果您想修改代码并更改要过滤的范围或字段,我在代码中标记了 4 个位置。相应地更改变量。
推荐阅读
- java - Java - sc.nextDouble() - 换行
- php - Vimeo API 获取结果为空的请求
- c# - 保存前设置值
- string-formatting - 字符串末尾的百分比-S (%s) 有什么用?(不是字符串格式)
- swift - 在 Swift 4.0 中 - 从代码添加时不会出现圆形
- javascript - 从数据库中获取月份并使用 javascript / ajax 发送到另一个页面?
- php - 计算多个表的行并单独返回结果?
- hibernate - java.lang.NoSuchMethodError: org.hibernate.StatelessSession.createQuery(Ljava/lang/String;)Lorg/hibernate/query/Query;
- java - 如何在Java中添加一系列数字
- python - Pandas 散点图 TypeError