通配符匹配

时间:2012-02-15 12:26:37

标签: vba excel-2007

我有两个问题。需要一些指导。

1)在VBA中使用LIKE运算符时如何使用Matchcase。以下代码仅与单词的确切形式匹配。我想我必须使用.MatchWildcards = False,但不知道如何/在哪里使用它。 例如: 搜索“德克萨斯”但这并没有考虑“德州人”。

2)我只需要找到“Texas”而不是“TexasRangers”这个词。有没有办法可以做到这一点,我该如何修改我的代码。

Sub Example()
   Dim wsh As Worksheet, i As Long, lngEndRowInv As Long
   Set wsh = ActiveSheet
   i = 2
   Lastr= wsh.Range("A" & wsh.Rows.Count).End(xlUp).Row
   While i <= Lastr
      If (Cells(i, "F") Like "*New Orleans*") And (Cells(i, "D") Like "*Belfast*") Then
           Cells(i, "C").Value = "Deleted"
           Cells(i, "C").Font.Color = vbRed
      ElseIf Not ((Cells(i, "A") Like "*Texas*") Or (Cells(i, "A") Like "*NY*")) Then
           Cells(i, "A").Value = "Not Deleted"
        End If
        i = i + 1
      Wend
End Sub

1 个答案:

答案 0 :(得分:2)

MatchWildcards是查找/替换对象模型的一部分,因此它不适用于VBA的LIKE

对于区分大小写,强制执行特定案例;

... ucase$((Cells(i, "A")) Like "*TEXAS*"

如果你想看一个单元格是否包含整个单词,同时考虑到周围的空白(你可以做'喜欢'),你可以;

dim re: set re = CreateObject("VBScript.RegExp")
re.pattern="\bTEXAS\b"
re.ignorecase=true

if re.test(Cells(i, "A")) then 
   //cell contains "TEXAS" in any case surrounded by a word boundary (white space, start/end of line).