匹配字符串中的完整单词

时间:2015-09-28 09:50:07

标签: excel vba for-loop vb-like-operator

我有以下代码,如果条件匹配,则使用服务填充偏移单元格。然而,在这个阶段,它的运作基础是,如果字符串出现在一个单元格中,它将应用值而不是单词是一个完整的单词。例如,我在我的标准中有“访问”,而“Vistor”(在一个单元格内)将遵守我的代码,而不应该。请有人帮忙吗?

Option Compare Text
Sub CHECK_CELL_VALUES()
    Dim LASTROW As Long
    Application.ScreenUpdating = False
        With Sheet1
        LASTROW = .Range("A1048576").End(xlUp).Row


            For i = 2 To LASTROW
                If Cells(i, 7).Value Like "*Service*" _
                Or Cells(i, 7).Value Like "*Servicing*" _
                Or Cells(i, 7).Value Like "* Labour*" _
                Or Cells(i, 7).Value Like "* Job*" _
                Or Cells(i, 7).Value Like "* Hire*" _
                Or Cells(i, 7).Value Like "* Visit*" _
                Or Cells(i, 7).Value Like "* Scaffold*" _
                Or Cells(i, 7).Value Like "* Contract*" _
                Or Cells(i, 7).Value Like "* Hour*" _
                Or Cells(i, 7).Value Like "* Month*" _
                Or Cells(i, 7).Value Like "* Quarter*" _
                Or Cells(i, 7).Value Like "* Day*" _
                Or Cells(i, 7).Value Like "* Maintenance*" _
                Or Cells(i, 7).Value Like "* Repair*" _
                Or Cells(i, 7).Value Like "* Survey*" _
                Or Cells(i, 7).Value Like "* Training*" _
                Or Cells(i, 7).Value Like "* Calibration*" _
                Then Cells(i, 7).Offset(0, 46).Value = "Service"
                Debug.Print Cells(i, 7).Address
            Next i

        End With
    Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:0)

我这样做的方式是: a)在要搜索的字符串之前和之后添加空格 b)搜索前后添加空格的字符串。 这是一个搜索单词VISIT的例子 它会匹配 “访问” “拜访” “拜访一下” 但会排除 “旅游”

InStr(1, " " & UCase(Sheets("Sheet1").Cells(i, 1)) & " ", " VISIT ")

答案 1 :(得分:-1)

尝试更改此内容:

If Cells(i, 7).Value Like "*Service*"

到此:

If InStr(Cells(i,7).Value,"Service") > 0

依此类推 - 这将匹配整个字符串"Service" InStr上的更多信息here