【Excel VBA】自定义一个增强版的vlookup函数
文章目录
我们知道Excel里有vlookup函数,但它只能返回第一个找到的对应,例如假设有以下数据:
要查找No为3对应的Content,使用vlookup函数,输入=VLOOKUP(D2,A1:B10,2,0),结果如下:
只返回了最先出现的结果"c"。如何能查找到所有内容呢?使用现有的Excel函数也绝对是可以实现的,但现在我们自己来写一个简单的函数完成这个功能。事先要明确一点,查找到的多个结果怎么组合在一起?字符不能像数字一样相加或者求平均,我们可以将其拼接在一起。
使用vba自定义一个vlookups函数,代码如下:
Option Explicit
Function vlookups(rng1 As Range, rng2 As Range, col As Byte, sep As String)
Dim time
time = Timer
Dim region, dict
Set rng1 = rng1(1)
Set dict = CreateObject("Scripting.Dictionary")
region = Intersect(rng2, ActiveSheet.UsedRange)
Dim target As String, r As Long
For r = LBound(region, 1) To UBound(region, 1)
'Debug.Print r
If region(r, 1) = rng1.Value Then
target = region(r, col)
'Debug.Print target
If Not dict.Exists(target) Then dict.Add target, ""
End If
Next
vlookups = Join(dict.Keys(), sep)
Debug.Print ((Timer - time) * 1000) & " ms"
End Function
原理就是遍历所查找的内容,将找到的内容依次存入字典,然后使用指定的分隔符sep拼接在一起,此时输入=vlookups(D5,A1:B10,2,"/"),前三个参数与vlookup是一样的含义,最后一个参数是分隔符,结果如下:

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论