SUMIFS的VBA代码?

我正在尝试编写一个自定义函数,使我能够从符合x个条件的范围的第一行中检索单元格。 我想这与SUMIFS的工作方式非常相似,只是比较简单,因为它不会在第一次匹配之后继续处理。

有没有人知道在VBA中重现SUMIFS(excel 07)函数的代码?

所以,举个例子,如果我有一个excel表格,比如:

WXYZ ab 6 1 ab 7 2 bb 7 3 

我想能够写一个函数,它会给我列Z的值,其中列W = a,X = b,Y> = 7(换句话说,值2)。

SUMIFS可以做到这一点,假设我想要的logging是独特的,我期待返回一个数字。 对我而言,这些假设是行不通的。

恕我直言,ADO不适合在Excel工作表函数中使用(性能差,不能在包含数据的工作表上使用)。 这里是一个VBA的替代scheme:

 Function MFind(theRange As Range, ParamArray Tests() As Variant) As Variant ' ' Parameters are: ' The Range to be searched ' the values to be searched for in successive columns ' all search values except the last use = ' the last search value uses >= ' the function returns the value from the last column in the range ' Dim vArr As Variant Dim j As Long Dim k As Long Dim nParams As Long Dim blFound As Boolean 

Function MFind(theRange As Range, ParamArray Tests() As Variant) As Variant ' ' Parameters are: ' The Range to be searched ' the values to be searched for in successive columns ' all search values except the last use = ' the last search value uses >= ' the function returns the value from the last column in the range ' Dim vArr As Variant Dim j As Long Dim k As Long Dim nParams As Long Dim blFound As Boolean

 vArr = theRange.Value2 nParams = UBound(Tests) - LBound(Tests) + 1 If nParams >= UBound(vArr, 2) Then MFind = CVErr(xlErrValue) Exit Function End If For j = 1 To UBound(vArr) blFound = True For k = LBound(Tests) To nParams - 2 If vArr(j, k + 1) <> Tests(k) Then blFound = False Exit For End If Next k If blFound Then If vArr(j, nParams) >= Tests(nParams - 1) Then MFind = vArr(j, UBound(vArr, 2)) Exit For End If End If Next j 

结束function

一个使用ADO的例子。

 strFile = Workbooks(1).FullName strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _ & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";" Set cn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") cn.Open strCon 'I want to be able to write a function that will give me the value ' 'in column Z where columns W=a, X=b, Y>=7 ' '(in other words the value 2).' strSQL = "SELECT Top 1 Z " _ & "FROM [Sheet1$] " _ & "WHERE W='a' And X='b' And Y>=7" rs.Open strSQL, cn Result = rs.Fields("Z") 

Deeno,有这个UDF是非常有用的,但你也可以使用plain old =VLOOKUP()

VLOOKUP()只能通过查找一个“键”来工作,但是您可以在左边的辅助列中创build一个连接的键。 例如:

 WXYZ AA ab 6 ab6 1 ab 7 ab7 2 bb 7 bb7 3 

然后=VLOOKUP(A1,$Z$1:$AA$3,2,FALSE)如果A1有您正在查找的值。 如果你的数据比较复杂,你可以用一个未使用的字符(例如:一个pipe道)来join数据,所以你有一个| B | 6而不是ab6。