|
分享一段自定义函数,可理解为vlookup的加强版,可实现功能:
1、根据关键字模糊匹配;
2、根据关键字近似匹配。
如图所示
希望感兴趣的大佬可再完善下分享,谢谢!
- ' '自定义函数,有4个参数。
- ' '第1个是查找值
- ' '第2个是查找范围
- ' '第3个是查找结果在查找范围的第几列
- ' '第4个是匹配是否区分字母大小写,True区分,False不区分,默认不区分
- Function VlookupMe(ByVal strKey As String, _
- ByVal rngData As Range, _
- ByVal y As Long, _
- Optional ByVal m As Boolean = False) As String
- Dim i As Long, x As Long, aData
- Dim b As Boolean, intInstr As Long
- Dim strM, strRes
- Dim strMatches As String
-
- Set rngData = Intersect(rngData, rngData.Parent.UsedRange)
- aData = rngData.Value
- '判断是否区分字母大小写▼
- If m Then strM = vbBinaryCompare Else strM = vbTextCompare
- strRes = "#N/A" '初始值为错误值
- strMatches = "" '用于存储匹配的结果
-
- For i = 1 To UBound(aData) '循环遍历数据源每行记录
- b = True '逻辑标记初始化
- For x = 1 To Len(strKey) '遍历每个字符是否都存在
- intInstr = InStr(1, aData(i, 1), Mid(strKey, x, 1), strM)
- If intInstr = 0 Then
- '判断关键值在查询字符串中是否存在
- b = False '如果不存在,则标记值改为false,同时退出该层循环
- Exit For '没必要找下去了,退出该层循环
- End If
- Next x
- If b Then '如果逻辑标记仍然为true,说明全字匹配
- '将匹配的结果添加到字符串中,用逗号分隔
- strMatches = strMatches & "," & aData(i, y)
- End If
- Next i
-
- If Len(strMatches) > 0 Then
- '去除开头多余的逗号,返回多个匹配结果
- VlookupMe = Mid(strMatches, 2)
- Else
- '返回错误值
- VlookupMe = strRes
- End If
-
- Set rngData = Nothing: Erase aData
- End Function
复制代码
|
|