以下是一个示例代码,它将查找指定的字符串并返回匹配的结果:

Sub FindString()

Dim searchString As String
Dim foundCell As Range

searchString = 'Hello World'

Set foundCell = Cells.Find(What:=searchString, After:=ActiveCell, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If Not foundCell Is Nothing Then
    MsgBox 'Found at row ' & foundCell.Row & ' and column ' & foundCell.Column
Else
    MsgBox 'String not found'
End If

End Sub

在此示例中,我们使用 Cells.Find 方法来查找字符串。该方法有许多参数,这些参数可以配置搜索的方式。在此示例中,我们使用了以下参数:

  • What: 要查找的字符串
  • After: 从哪个单元格开始搜索
  • LookIn: 搜索的内容类型(例如,值或公式)
  • LookAt: 匹配类型(例如,完全匹配或部分匹配)
  • SearchOrder: 搜索顺序(按行或按列)
  • SearchDirection: 搜索方向(向上或向下)
  • MatchCase: 大小写敏感
  • SearchFormat: 是否考虑单元格格式

如果找到了匹配项,则会返回包含该单元格的 Range 对象。如果未找到匹配项,则返回 Nothing。在此示例中,我们使用了 MsgBox 函数来显示结果。你可以根据需要修改代码,以便将结果输出到单元格或其他位置。

Excel VBA 查找字符串并返回结果 - 代码示例

原文地址: https://www.cveoy.top/t/topic/oYrQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录