【问题标题】:vba: if cell contains whole word thenvba:如果单元格包含整个单词,则
【发布时间】:2018-08-14 10:43:08
【问题描述】:

您好,我正在尝试编写一段代码来识别字符串 cell(2,5) = "This situation is bad"cell(3,5) = "我想坐下" 包含单词“坐下”。

理想情况下,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?

【问题讨论】:

  • 您的单词会用空格或标点符号填充吗?

标签: excel vba


【解决方案1】:

考虑:

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

这假设缺少像 sit.sit?

这样的标点符号

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多