從根本上說,我會用一個For Each ... In ... Next
循環,在第一次發現中斷。這裏是沒有太多的錯誤檢查工作草案(TargetRange只有1行,TargetCell是一個字符串,用Ucase/LCASE,等...):
Function FirstMatch(TargetRange As Range, SearchString As String) As Variant
Dim TargetCell As Range
' if we don't find any, we return a #N/A error value
FirstMatch = CVErr(xlErrNA)
For Each TargetCell In TargetRange.Cells
If InStr(1, TargetCell, SearchString) Then
' returning the value of first find
' FirstMatch = TargetCell
' returning the column position relative to the first cell in selected range
FirstMatch = TargetCell.Column - TargetRange(1, 1).Column + 1
Exit Function
End If
Next TargetCell
End Function
使用您的情況是:
A2 :=FirstMatch(C2:F2, "str")
修改If ...
狀況根據自己的需要(如Left(...)
等)
使用功能,您避免硬編碼(壞壞壞)!
謹慎一句:Allthough For Each ... In ... Next
doesn't guarantee a strictly sequential processing我一直覺得很安全,而中等大小的1維範圍使用時。如果你想確定你需要引入一個索引變量並使用一個普通的循環。
爲什麼向下票呢?解釋一下 – karamell