[英]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.