Extended/Replacement DLookup()

        19 votes: *****     22,371 views      No comments
by Allen Browne, 20 April 2005    (for Access 95+)

Microsoft Access Tips for Serious Users

Provided by Allen Browne, November 2003.  Updated April 2010.

Extended DLookup()

The DLookup() function in Access retrieves a value from a table. For basic information on how to use DLookup(), see Getting a value from a table.

Why a replacement?

DLookup() has several shortcomings:

  1. It just returns the first match to finds. Since you cannot specify a sort order, the result is unpredictable. You may even get inconsistent results from the same data (e.g. after compacting a database, if the table contains no primary key).
  2. Its performance is poor.
  3. It does not clean up after itself (can result in Not enough databases/tables errors).
  4. It returns the wrong answer if the target field contains a zero-length string.

ELookup() addresses those limitations:

  1. An additional optional argument allows you to specify a sort order. That means you can specify which value to retrieve: the min or max value based on any sort order you wish to specify.
  2. It explicitly cleans up after itself.
  3. It runs about twice as fast as DLookup(). (Note that if you are retrieving a value for every row of a query, a subquery would provide much better performance.)
  4. It correctly differentiates a Null and a zero-length string.

Limitations of ELookup():

  1. If you ask ELookup() to concatenate several (not memo) fields, and more than 255 characters are returned, you strike this Access bug:
          Concatenated fields yield garbage in recordset.
  2. DLookup() can call the expression service to resolve an argument such as:
        DLookup("Surname", "Clients", "ClientID = [Forms].[Form1].[ClientID]")

You can resolve the last issue by concatenating the value into the string:
    ELookup("Surname", "Clients", "ClientID = " & [Forms].[Form1].[ClientID])

Before using ELookup() in a query, you may want to modify it so it does not pop up a MsgBox for every row if you get the syntax wrong. Alternatively, if you don't mind a read-only result, a subquery would give you faster results than any function.

How does it work?

The function accepts exactly the same arguments as DLookup(), with an optional fourth argument. It builds a query string:
    SELECT Expr FROM Domain WHERE Criteria ORDER BY OrderClause

This string opens a recordset. If the value returned is an object, the requested expression is a multi-value field, so we loop through the multiple values to return a delimited list. Otherwise it returns the first value found, or Null if there are no matches.

Note that ELookup() requires a reference to the DAO library. For information on setting a reference, see References.

Public Function ELookup(Expr As String, Domain As String, Optional Criteria As Variant, _
    Optional OrderClause As Variant) As Variant
On Error GoTo Err_ELookup
    'Purpose:   Faster and more flexible replacement for DLookup()
    'Arguments: Same as DLookup, with additional Order By option.
    'Return:    Value of the Expr if found, else Null.
    '           Delimited list for multi-value field.
    'Author:    Allen Browne. allenbrowne.com
    'Updated:   December 2006, to handle multi-value fields (Access 2007 and later.)
    '           1. To find the last value, include DESC in the OrderClause, e.g.:
    '               ELookup("[Surname] & [FirstName]", "tblClient", , "ClientID DESC")
    '           2. To find the lowest non-null value of a field, use the Criteria, e.g.:
    '               ELookup("ClientID", "tblClient", "Surname Is Not Null" , "Surname")
    'Note:      Requires a reference to the DAO library.
    Dim db As DAO.Database          'This database.
    Dim rs As DAO.Recordset         'To retrieve the value to find.
    Dim rsMVF As DAO.Recordset      'Child recordset to use for multi-value fields.
    Dim varResult As Variant        'Return value for function.
    Dim strSql As String            'SQL statement.
    Dim strOut As String            'Output string to build up (multi-value field.)
    Dim lngLen As Long              'Length of string.
    Const strcSep = ","             'Separator between items in multi-value list.

    'Initialize to null.
    varResult = Null

    'Build the SQL string.
    strSql = "SELECT TOP 1 " & Expr & " FROM " & Domain
    If Not IsMissing(Criteria) Then
        strSql = strSql & " WHERE " & Criteria
    End If
    If Not IsMissing(OrderClause) Then
        strSql = strSql & " ORDER BY " & OrderClause
    End If
    strSql = strSql & ";"

    'Lookup the value.
    Set db = DBEngine(0)(0)
    Set rs = db.OpenRecordset(strSql, dbOpenForwardOnly)
    If rs.RecordCount > 0 Then
        'Will be an object if multi-value field.
        If VarType(rs(0)) = vbObject Then
            Set rsMVF = rs(0).Value
            Do While Not rsMVF.EOF
                If rs(0).Type = 101 Then        'dbAttachment
                    strOut = strOut & rsMVF!FileName & strcSep
                    strOut = strOut & rsMVF![Value].Value & strcSep
                End If
            'Remove trailing separator.
            lngLen = Len(strOut) - Len(strcSep)
            If lngLen > 0& Then
                varResult = Left(strOut, lngLen)
            End If
            Set rsMVF = Nothing
            'Not a multi-value field: just return the value.
            varResult = rs(0)
        End If
    End If

    'Assign the return value.
    ELookup = varResult

    Set rs = Nothing
    Set db = Nothing
    Exit Function

    MsgBox Err.Description, vbExclamation, "ELookup Error " & Err.number
    Resume Exit_ELookup
End Function

Home Index of tips Top

Rate this article:  Your rating: PoorYour rating: Not so goodYour rating: AverageYour rating: GoodYour rating: Excellent

This is a cached tutorial, reproduced with permission.

Have your say - comment on this article.

What did you think of 'Extended/Replacement DLookup()'?

No comments yet.

Why not be the first to comment on this article?!

Have your say...

E-mail (e-mail address will be kept private)

Comments require approval before being displayed on this page (allow 24 hours).