以下是使用 VBA 在 Excel 工作表中查找字符串的示例代码:

Sub findString()

Dim searchString As String
Dim searchRange As Range
Dim foundCell As Range

searchString = InputBox('Please enter the string you want to find:', 'Find String')

If searchString = "" Then Exit Sub

Set searchRange = ActiveSheet.Cells

Set foundCell = searchRange.Find(what:=searchString, LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False)

If Not foundCell Is Nothing Then
    foundCell.Activate
    MsgBox 'The string '' & searchString & '' was found in cell ' & foundCell.Address
Else
    MsgBox 'The string '' & searchString & '' could not be found in the worksheet.'
End If

End Sub

该代码将提示用户输入要查找的字符串,然后在当前活动工作表的所有单元格中查找该字符串。如果找到了该字符串,它将激活包含该字符串的单元格,并显示一个消息框,指示该字符串在哪个单元格中被找到。如果在整个工作表中找不到该字符串,则显示一个消息框,指示该字符串无法找到。

代码详解:

  1. 变量定义:

    • searchString: 用于存储用户输入的查找字符串。
    • searchRange: 用于指定查找范围,这里设置为当前活动工作表的所有单元格。
    • foundCell: 用于存储找到的字符串所在单元格。
  2. 用户输入:

    • searchString = InputBox('Please enter the string you want to find:', 'Find String'):使用 InputBox 函数提示用户输入要查找的字符串。
  3. 查找过程:

    • Set searchRange = ActiveSheet.Cells: 将 searchRange 变量设置为当前活动工作表的 Cells 对象,即所有单元格。
    • Set foundCell = searchRange.Find(what:=searchString, LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False): 使用 Find 方法在 searchRange 中查找 searchString。参数说明:
      • what: 要查找的字符串。
      • LookIn: 指定查找范围,这里设置为 xlValues,表示在单元格的值中查找。
      • LookAt: 指定匹配方式,这里设置为 xlPart,表示查找部分匹配的字符串。
      • MatchCase: 指定是否区分大小写,这里设置为 False,表示不区分大小写。
  4. 结果处理:

    • If Not foundCell Is Nothing Then: 如果 foundCell 不为空,表示找到了字符串。
      • foundCell.Activate: 激活找到的单元格。
      • MsgBox 'The string '' & searchString & '' was found in cell ' & foundCell.Address: 显示消息框,指示字符串在哪个单元格中被找到。
    • Else: 如果 foundCell 为空,表示没有找到字符串。
      • MsgBox 'The string '' & searchString & '' could not be found in the worksheet.': 显示消息框,指示字符串无法找到。

该代码示例简洁明了,并提供了清晰的注释说明。您可以根据需要修改查找范围、匹配方式和大小写敏感性设置。

Excel VBA 查找字符串:完整代码示例与说明

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

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