我有两个工作表,我试图比较,看看是否在wksht2中找到wksht1的值。
For Each c In wksht2
If WorksheetFunction.CountIf(wksht1, c.Value) > 0 Then
sh2.Range("j10") = c.Value
End If
Next
如果找到,则返回在wksht1中找到的值。 例如: 假设我有两个列表
清单1:
名称:1,Name3,Name17,Name85
清单2:
Name12,Name6,Name3
将列表2与列表1进行比较,我会发现在列表1中找到“Name3”,上面的函数将在单元格J10中返回“Name3”。
但是我还需要确定找到它的位置......例如,在这个例子中,列表1中“Name3”的位置将是位置2.
那么,我如何搜索字符串,如果找到它,确定它所在的单元格?
答案 0 :(得分:1)
此函数将查找给定val
Function where(rng As Range, val As Variant) As String
Dim r As Range
Set r = rng.Find(val)
If r Is Nothing Then
where = val & " was not found"
Else
where = r.address
End If
End Function
Sub TestIt()
Debug.Print where(Sheet1.UsedRange, "abcde")
End Sub
编辑:这是一个版本,它将以逗号分隔的字符串(csv)为您提供所有匹配的地址:
Function whereAll(rng As Range, val As Variant) As String
Dim r As Range, firstFound As String
Set r = rng.Find(val)
If r Is Nothing Then Exit Function
firstFound = r.address
Do
whereAll = whereAll & "," & r.address
Set r = rng.FindNext(r)
Loop Until r.address = firstFound
whereAll = Mid(whereAll, 2, 100000)
End Function