|
XLOOKUP函数功能强大,无奈桌面版本都用不了,一时兴起自己动手山寨了一个,主要实现了反向查找、逆序查找和自定义找不到返回值的功能,官方文档中描述的[match_mode]非0的场景感觉太复杂,鉴于没有365试验,先忽略掉了;[search_mode]用二分法那俩参数我也先忽略了,主要能逆向就行。
- Option Explicit
- Function XLOOKUP(ByRef lookup_value As Variant, ByRef lookup_array As Range, ByRef return_array As Range, Optional ByRef if_not_found As Variant, Optional ByVal match_mode As Integer = 0, Optional ByVal search_mode As Integer = 1)
- Dim FormulaString As String, separator As String
-
- If search_mode = 1 Then
- If lookup_array.Columns.Count = 1 Then
- FormulaString = "VLOOKUP("
- separator = ","
- ElseIf lookup_array.Rows.Count = 1 Then
- FormulaString = "HLOOKUP("
- separator = ";"
- End If
- FormulaString = FormulaString & Get_String(lookup_value) & ",if({1" & separator & "0}," & lookup_array.Address(External:=True) & "," & return_array.Address(External:=True) & "),2,0)"
- ElseIf search_mode = -1 Then
- FormulaString = "LOOKUP(1,0/(" & lookup_array.Address(External:=True) & "=" & Get_String(lookup_value) & ")," & return_array.Address(External:=True) & ")"
- End If
-
- If Not IsMissing(if_not_found) Then FormulaString = "IFERROR(" & FormulaString & "," & Get_String(if_not_found) & ")"
- FormulaString = "=" & FormulaString
-
- XLOOKUP = Evaluate(FormulaString)
- End Function
- Private Function Get_String(ByRef v As Variant)
- If TypeName(v) = "Range" Then
- Get_String = v.Address(External:=True)
- Else
- Get_String = """" & v & """"
- End If
- End Function
复制代码 代码比较粗糙,欢迎批评指正和补充完善!
|
|