我有10列(不要打扰列)和超过10,000行。行中的数据如下:
男士黑色 Pindot 紧身燕尾服裤子
男士粉红色罗纹肌肉贴合毛衣
Mens Gold Look Bug Lapel Pin
男士黑色 Pin 后背领结
问题是: 我想过滤“Pin”字样。这意味着过滤后的结果应该只提供我提到的最后两行,而不是包含“Pinkdot”和“Pink”的行
任何帮助将不胜感激。感谢
答案 0 :(得分:3)
尝试下面的代码(使用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
使用多个单词,并仅将特定单词的字体用红色(而不是enitre单元格)
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
答案 1 :(得分:2)
给出了一些好的VBA解决方案。这是公式选项,如果找到True
,则为Pin
,否则为False
(它不区分大小写)。
如果您在A1
中有字符串,则可以将其放在B1
中并向下拖动。 (您可以将其放在K1
或其他任何内容中,如果这更容易)
=OR(OR(LEFT(A1,4)="Pin ",RIGHT(A1,3)="pin"),NOT(ISERROR(SEARCH(" pin ",A1))))
以下是它的工作原理:
pin
(后面有空格),或者在字符串末尾可以找到pin
。pin
(两边都有空格)。显然,此时您只需过滤True
值。
答案 2 :(得分:0)
您可以使用AutoFilter。 使用或 条件,您可以说您希望所有 Pin 在Word之后有空格或空格。所以你可以得到所有 Pin 字。
代码看起来像这样:
ActiveSheet.ListObjects("Tabelle1").Range.AutoFilter Field:=1, Criteria1 _
:="=** Pink**", Operator:=xlOr, Criteria2:="=**Pink **"
答案 3 :(得分:0)
使用自动过滤器时:
文字过滤器&gt;自定义过滤器...&gt;
contains ▼ |Pin | '(this contains a single space after the word)
○ And ◙ Or
ends with ▼ |Pin| '(without the single space)
这将为您提供所需的结果