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

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

因此,例如,如果我在excel中有一个表,如:

W X Y Z
a b 6 1
a b 7 2
b b 7 3

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

SUMIFS可以大致这样做,假设我想要的记录是唯一的,我想要返回一个数字。但就我的目的而言,这些假设是行不通的。

有帮助吗?

解决方案

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


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

结束功能

其他提示

使用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是非常有用的,但你也可以使用普通的旧 = VLOOKUP()

VLOOKUP()只能通过查找一个“密钥”来工作。但是你可以在左边的帮助列中创建一个连锁键。例如:

W X Y Z    AA
a b 6 ab6  1
a b 7 ab7  2
b b 7 bb7  3

然后 = VLOOKUP(A1,$ Z $ 1:$ AA $ 3,2,FALSE)如果A1有你想要的值。如果您的数据更复杂,您可以使用未使用的字符(例如:管道)加入数据,因此您有| B | 6而不是ab6。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top