2012-02-23 428 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

相關問題