2012-02-23 426 views
1

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

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) 

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

欢迎任何建议!

+1

嗯,仔细研究Instr函数,它不能等于1,它会更高,我对此印象深刻函数为1 = true,0 = false。 – CustomX 2012-02-23 16:22:49

+0

'Instr'返回您正在搜索的字符串中第一次出现字符串的位置 – barrowc 2012-03-03 02:25:01

回答

4

难道你不只是搜索子字符串?

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 
+0

因此,它会搜索我的整个表格以寻找'5/7 binnen 4h'? – CustomX 2012-02-23 16:27:31

+0

是的,比单独查看单元格循环要快得多。 – 2012-02-23 16:31:36

+0

我该怎么实现呢?我不断收到错误:s – CustomX 2012-02-23 16:33:46

2

这是太适应一个评论,因此发布它作为答案...

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

作为一个例子(与纸张加工含有B4文本“你好汤姆”:

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()“手动”,然后在同一会话中稍后在代码中使用它(虽然没有测试)

+0

有趣!我不知道。那里有一点设计的哑巴! – 2012-02-23 23:07:48

+0

这实际上是有道理的。它必须默认找到单元格内容的完全匹配,所以如果你指定'lookat:= xlWhole'或者如果你留下空白,它会尝试匹配,并且“tom”与“hello tom”不完全匹配。这是一个部分匹配,这就是为什么'lookat:= xlPart'可以工作。 – 2016-03-05 17:51:19

相关问题