繁体   English   中英

Excel VBA - 检查单元格是否包含文本

[英]Excel VBA - Check cell whether it contains piece of text

我想检查某段文本的一系列单元格。 这个文本总是在我的文档中,除了它的单元格是可变的(列始终是B)。 因此,我检查从1:75开始的范围是否有任何单元格包含一段文本,但它似乎不起作用。

Dim FoundRange As Range
Set FoundRange = Cells.Find("5/7 binnen 4h")
Range("I" & EmptyCell + 2).Value = ... (value of cell I on same row as B)

我正在寻找的Cell总是包含这个文本Onderhoud 5/7 binnen 4h但它的位置可以变化,这就是为什么我只需要检查它是否包含任何一个。 当我找到那个单元格时,我需要在同一行上的值I。

欢迎任何建议!

你能不能只搜索子串?

Sheet1.Cells.Find("string to find")

将返回包含字符串的范围(如果找不到字符串,则返回任何内容。

例如

Public Sub Macro1()
Dim FoundRange As Range

Set FoundRange = Sheet1.Cells.Find("5/7 binnen 4h")

' display the cell address to the user
MsgBox FoundRange.Address


' put the found value in column i in the same row as the found text in a known location ($C$1 in this case)
Sheet1.Range("$C$1").Value = Sheet1.Cells(FoundRange.Row, 9).Value

' put the found value in four columns to the right in the same row as the found text in a known location ($C$1 in this case)
Sheet1.Range("$C$2").Value = FoundRange.Offset(0, 4).Value

End Sub

这太过于不适合评论,所以将其作为答案发布......

使用只有一个参数的Find()时应该小心:如果你之前在代码中使用了Find()并且(例如)指定了一个参数lookat:=xlWhole那么你可能得不到你期望的结果,特别是如果你正在寻找一个单元格值的子串。 传递给Find()的设置是持久的:如果您没有指定参数,那么它可能会从之前的使用中继承。

作为一个例子(使用包含B4中文本“hello tom”的工作表:

Sub Tester()

    Dim f

    Set f = ActiveSheet.Cells.Find(what:="tom", lookat:=xlPart)
    Report f

    Set f = ActiveSheet.Cells.Find(what:="tom", lookat:=xlWhole)
    Report f

    Set f = ActiveSheet.Cells.Find("tom")
    Report f

End Sub

Sub Report(f)
    If Not f Is Nothing Then
        Debug.Print f.Address
    Else
        Debug.Print "not found"
    End If
End Sub

运行这个给出:

$B$4
not found
not found

我似乎记得如果你已经“手动”使用了Find(),然后在同一个会话中稍后在代码中使用它(虽然没有测试)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM