
这里以A:K列为源数据区域,单元格L5以下列返回模糊查找的值,单元格M5以下列返回结果所在的位置,当点击按钮时弹出输入框,确定后返回结果。
以下是源代码:
Sub findAll()
Dim findsm As String, address As String
Dim sc As Range, rs As Range, fCount As Long
findsm = InputBox("找什么(⊙o⊙)?")
If Len(findsm) > 0 Thens
clearFinds
Set sc = Range("a1").CurrentRegion
Set rs = sc.find(What:=findsm)
If Not rs Is Nothing Then
address = rs.address
Do
Range("L5").Offset(fCount).Value = rs.Value
Range("M5").Offset(fCount).Value = rs.address
Set rs = sc.FindNext(rs)
fCount = fCount + 1
Loop While Not rs Is Nothing And rs.address<>address
End If
End If
End Sub
....执行清空...
Sub clearFinds()
Range(Range("L5:M5"), Range("L5:M5").End(xlDown)).Clear
End Sub
此代码用了一个自定义函数,在循环查找这里可能有些不好理解:
If Not rs Is Nothing Then address = rs.address...匹配到赋值(单元格所在位置)给变量...
Do
Range("L5").Offset(fCount).Value = rs.Value
...返回值...
Range("M5").Offset(fCount).Value = rs.address
...返回位置...
Set rs = sc.FindNext(rs) fCount = fCount + 1...继续遍历剩余字符串...
Loop While Not rs Is Nothing And rs.address<>address End If...遍历所有字符串停止... 说明:由于附件是启用了宏的工作簿,所以建议先打开Excel宏。