vba:如果单元格包含整个单词,则

时间:2018-08-14 10:43:09

标签: excel vba

嗨,我正在尝试编写一段代码来识别字符串 cell(2,5)=“这种情况不好” cell(3,5)=“我想坐下” 包含单词“ sit”。

理想情况下,cell(2,5)将返回0,cell(3,5)将返回1。

现在我有

for i = 2 to 3
  if LCase(cells(i,5)) like "*sit*" then
  cells(2,5) = 1
  end if
next i

问题是cell(2,5)包含单词“ situation”,因此为“ sit”,在这种情况下,我的代码将返回1。

我也尝试过

if instr(1,cells(i,5),"sit") <> 0 then
cells(i,5) = 1

给出相同的错误结果

我想知道,当且仅当单元格包含整个单词时,我才能返回1吗?

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式,因为您希望找到一个不仅是子字符串的单词。当前,此结果将输出到相邻的右栏中。

Option Explicit
Public Sub IsWordFound()
    Dim arr(), i As Long
    With Worksheets("Sheet1")
        arr = .Range("E2:E3").Value
        ReDim Preserve arr(1 To UBound(arr, 1), 1 To UBound(arr, 1))
        For i = LBound(arr, 1) To UBound(arr, 1)
            arr(i, 2) = IsFound(arr(i, 1), "sit")
        Next i
       .Range("E2").Resize(UBound(arr, 1), UBound(arr, 2)) = arr
    End With
End Sub

Public Function IsFound(ByVal inputString As String, ByVal word As String) As Byte
    Dim  re As Object
    Set re = CreateObject("VBScript.RegExp")
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = "\b" & word & "\b"
        If .test(inputString) Then
           IsFound = 1
        Else
           IsFound = 0
        End If
    End With
End Function

答案 1 :(得分:0)

考虑:

Public Function CheckForSit(inpt As String) As Long
    Dim examin As String, patrn As String

    examin = " " & LCase(inpt) & " "
    patrn = " sit "

    If InStr(examin, patrn) > 0 Then
        CheckForSit = 1
    Else
        CheckForSit = 0
    End If
End Function

enter image description here

这假设没有标点符号,例如 sit。 sit?