在Excel中筛选来自string的单词

我有10列(不要打扰列)和超过10,000行。 行中的数据如下所示:

男士黑色平底鞋紧身适合的燕尾服裤子

男装粉红罗纹肌肉适合毛衣

男装黄金看起来不错的翻领别针

男士黑色背领结

问题是:我只想过滤“Pin”字。 这意味着过滤后的结果应该只给出我刚刚提到的最后2行,而不是包含“Pinkdot”和“Pink”的行

任何帮助将不胜感激。 谢谢

尝试使用下面的代码(使用RegEx对象查找与“Pin”完全匹配的内容)。

RegEx模式是.Pattern = "\bPin\b"

 Option Explicit Sub FindPinOnly() Dim C As Range Dim RegEx As Object, Match As Object Set RegEx = CreateObject("vbscript.regexp") With RegEx .MultiLine = False .Global = True .IgnoreCase = True .Pattern = "\bPin\b" ' Match exactly "Pin" without extra letters End With For Each C In Range("A1:J10000") '<-- loop through all cells in Range Set Match = RegEx.Execute(C.Value) If Match.Count >= 1 Then C.Interior.ColorIndex = 46 '<-- in my tests I just colored the cells in Red End If Next C End Sub 

注意 :不要害怕这里的循环,花费不到一秒钟的时间来完成这段代码的运行。


编辑1 :允许在多个单词中使用RegEx ,并且只将特定单词的字体以红色(而不是单元格)

 Option Explicit Sub TestRegex() ' This sub is to test the RegEx with multile words (from an array) Dim StrArr, Elem As Variant ' add words below to array (can add words to array using a Range of cells) StrArr = Array("Belt", "Shoes", "Sunglass", "Pin") For Each Elem In StrArr '<-- loop through all elements in array and use RegEx sub to find them in the Range Call FindWordOnly(Elem) Next Elem End Sub '======================================================================== Sub FindWordOnly(str As Variant) Dim C As Range Dim RegEx As Object, Match As Object Set RegEx = CreateObject("vbscript.regexp") With RegEx .MultiLine = False .Global = True .IgnoreCase = True .Pattern = "\b" & str & "\b" ' Match exactly "Pin" without extra letters End With For Each C In Range("A1:J10000") '<-- loop through all cells in Range Set Match = RegEx.Execute(C.Value) If Match.Count >= 1 Then ' === only modify the "found" text inside the cell to Red === Dim StartChar As Long StartChar = InStr(1, C.Value, str) C.Characters(Start:=StartChar, Length:=Len(str)).Font.Color = RGB(255, 0, 0) End If Next C End Sub 

一些好的VBA解决scheme给出。 这里是公式选项,它会给你一个True如果发现精确的Pin ,否则为False (不区分大小写)。

如果你在A1有一个string,你可以把它放在B1然后向下拖动。 (你可以把它放在K1或任何真的如果更容易)

 =OR(OR(LEFT(A1,4)="Pin ",RIGHT(A1,3)="pin"),NOT(ISERROR(SEARCH(" pin ",A1)))) 

这是如何工作的:

  1. 检查pin (后面有空格)是否可以在开始处find,或者是否可以在string的末尾find正确的pin
  2. 检查是否可以在string中间的某个位置findpin (两边都有空格)。
  3. 在任何一种情况下返回true,否则返回false。

很明显,在这一点上,你可以过滤True值。

您可以使用AutoFilter。 根据 标准,你可以说,你想要所有的Pin有一个空间的味道或Word后的空间。 所以你可以得到所有的拼音字。

该守则看起来像这样:

 ActiveSheet.ListObjects("Tabelle1").Range.AutoFilter Field:=1, Criteria1 _ :="=** Pink**", Operator:=xlOr, Criteria2:="=**Pink **" 

使用自动filter时:

文本filter>自定义filter…>

 contains ▼ |Pin | '(this contains a single space after the word) ○ And ◙ Or ends with ▼ |Pin| '(without the single space) 

这会给你想要的结果