首页 > 解决方案 > 在整行中查找部分文本

问题描述

我正在尝试在整行中搜索包含“PROFILE”的字符串。它总是大写,但格式为,例如“[9]PROFILE001”。

一些额外的信息:我使用了 Find 命令来定位我正在搜索字符串的行。它有自己的变量,我试图将其合并到我正在使用的范围中。

我在这里搜索了多个部分字符串文章,但无法将其实现到我的代码中。我尝试使用 Like 命令和 IntStr 命令无济于事。我相信我的问题可能与我如何引用搜索范围或我如何搜索有关。

这是我当前代码的片段:

'finding item name row
Set FindRow3 = Range("A1:A100").Find("Item Name", LookIn:=xlValues)
itemnamerow = FindRow3.Row
'The section above is working as intended

'searching for the word profile, the section below is the one I am having issues with
Range("B8:Z100").Style = "Normal"
If ActiveSheet.Range("B" & itemnamerow & ":Z" & itemnamerow) Like "*PROFILE" Then
    Range("C1").Value = "it worked"
End If

我目前遇到运行时错误 13,在“If ActiveSheet...”行中键入不匹配。我无法获得正确的索引以使其正确。

我正在尝试使用它,如果找到部分字符串,我想做点什么。

TIA

标签: excelvba

解决方案


您需要使用Find方法,设置MatchCaseLookIn参数。并且可能LookAt是为了确保它检查实际值而不是公式语法。

Dim profileFound as Range
Set profileFound = ActiveSheet.Range("B" & itemnamerow & ":Z" & itemnamerow).Find("PROFILE",lookIn:=xlValues,MatchCase:=True,lookAt:=xlPart)

If Not profileFound is nothing Then
    debug.print profileFound.Value
    Range("C1").Value = "it worked"
else
    debug.print "no profile found"
End If

原始代码失败的原因是 Excel 不允许您针对单个值评估多单元格范围。您可以遍历范围内的每个单元格并单独检查每个单元格,但既然Find可用,那是多余的。


推荐阅读