首页 > 解决方案 > “查找”命令的表达式

问题描述

我想使用“查找”命令一次搜索一个单元格,而不是一次搜索一个单元格范围。我尝试使用如下所示的“For Each”命令,但它不起作用。是否可以使用其他表达式搜索单词,例如使用“范围”Set rgFound = activecell.Find("John")或 “范围”?Set rgFound = cells(1,1).Find("John"))

Sub tester()
    Dim rgFound As Range
    Set rng = Columns(1)
    Set rng1 = rng.SpecialCells(xlVisible)

    For Each cell In rng1
        Set rgFound = cell.Find("John")
        If rgFound Is Nothing Then
            MsgBox "Name was not found."
        Else
            MsgBox "Name found in :" & rgFound.Address
        End If
    Next
End Sub

标签: excelvba

解决方案


要搜索单个单元格的值,您必须使用InStr 函数

If InStr(1, Range("A1").Value, "John", vbTextCompare) > 0 Then
    'John was found
Else
    'John was not found
End If

InStr返回在单元格 A1 的值中找到的第一个位置John,所以如果它返回一个数字,> 0那么它就没有找到。


或者,您可以使用Like 运算符

If Range("A1").Value Like "*John*" Then
    'John was found
Else
    'John was not found
End If

注意周围的占位符(*星号),以确保类似的操作员John"any string that conains John in the begining middele or end of the string"


推荐阅读