从根本上说,我会在第一次查找时使用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(...)
等)
使用一个函数可以避免硬编码(坏坏坏)!
提醒一句:尽管For Each ... In ... Next
不能保证严格的顺序处理,但我总是发现它在与中等大小的一维范围一起使用时相当安全。如果您想绝对确定需要引入索引变量并使用普通For ... Next
循环。