2014-11-14 27 views
0

我想正確使用2d udf。用於使用sumproduct不起作用的2d查找的udf

= blookup(namedrange,HLOOKUP,VLOOKUP)

我寫了下面的,但它無法正常工作。請幫忙。

Function blookup(r, h, v) 
Dim a, b, c, t, w 
Dim r_count As Integer 
Dim c_count As Integer 
Dim x As Variant 
r_count = r.Rows.Count 
c_count = r.Columns.Count 
t = r.Worksheet.name & "!" 
a = r.Cells(2, 2).Address & ":" & r.Cells(r_count, c_count).Address 
b = r.Cells(1, 2).Address & ":" & r.Cells(1, c_count).Address 
c = r.Cells(2, 1).Address & ":" & r.Cells(r_count, 1).Address 
x = Evaluate("=sumproduct(((" & t & b & ")=" & h & ")*((" & t & c & ")=" & v & ")*(" & t & a & "))") 
blookup = x 
End Function 

回答

0

看起來像現在的工作,但我仍然懷疑它可能會打破。

Function blookup(r As Range, h As String, v As String) As Variant 
Dim a, b, c, t, w 
Dim r_count As Integer 
Dim c_count As Integer 
Dim x As Variant 
r_count = r.Rows.Count 
c_count = r.Columns.Count 
t = r.Worksheet.name & "!" 
a = r.Cells(2, 2).Address & ":" & r.Cells(r_count, c_count).Address 
b = r.Cells(1, 2).Address & ":" & r.Cells(1, c_count).Address 
c = r.Cells(2, 1).Address & ":" & r.Cells(r_count, 1).Address 
x = Evaluate("sumproduct(((" & t & b & ")=" & Chr(34) & h & Chr(34) & ")*((" & t & c & ")=" & Chr(34) & v & Chr(34) & ")*(" & t & a & "))") 
blookup = x 
End Function 
0

我意識到sumproduct不能用於非數字數據,所以我用vlookup和match編寫了另一個版本。

Function blookup(r As Range, v As Variant, h As Variant) As Variant 
Dim a As String, b As String, c As String, t As String, f As Variant, eh As String, ev As String 
Dim r_count As Integer 
Dim c_count As Integer 
Dim x As String 
r_count = r.Rows.Count 
c_count = r.Columns.Count 
If VarType(h) = vbDate Then eh = "Datevalue" 
If VarType(v) = vbDate Then ev = "datevalue" 
t = "'" & r.Worksheet.name & "'!" 
a = r.Cells(2, 1).Address & ":" & r.Cells(r_count, c_count).Address 
b = r.Cells(1, 1).Address & ":" & r.Cells(1, c_count).Address 
x = "vlookup(" & ev & "(" & Chr(34) & v & Chr(34) & ")," & t & a & ", match(" & eh & "(" & Chr(34) & h & Chr(34) & ")," & t & b & ",0),false)" 
f = Evaluate(x) 
blookup = f 
End Function