Public Function DCount(ByVal Expr As String, ByVal Domain As String, Optional ByVal Criteria As Variant, _
Optional ByVal Distinct As Boolean = False) As Variant
If Distinct Then
DCount = LookupSql("select Count(" & Expr & ") from (" & BuildSelectSql(Expr, Domain, Criteria, True) & ")")
Else
DCount = Application.DCount(Expr, Domain, Criteria)
End If
End Function
Private Function BuildSelectSql(ByVal Expr As String, ByVal Domain As String, Optional ByVal Criteria As Variant, _
Optional ByVal Distinct As Boolean = False)
Dim SelectSql As String
SelectSql = "SELECT "
If Distinct Then
SelectSql = SelectSql & "Distinct "
End If
SelectSql = SelectSql & Expr & " FROM (" & Domain & ")"
If Not IsMissing(Criteria) Then
If Len(Criteria) > 0 Then
SelectSql = SelectSql & " WHERE " & Criteria
End If
End If
BuildSelectSql = SelectSql
End Function
Public Function LookupSql(ByVal SqlText As String, _
Optional ByVal Index As Variant = 0&, _
Optional ByVal ValueIfNull As Variant = Null, _
Optional ByVal DatabaseToUse As DAO.Database = Nothing) As Variant
Dim rst As DAO.Recordset
On Error GoTo HandleErr
If DatabaseToUse Is Nothing Then
Set DatabaseToUse = CurrentDb
End If
Set rst = DatabaseToUse.OpenRecordset(SqlText, dbOpenForwardOnly, dbSeeChanges, dbReadOnly)
With rst
If .EOF Then
LookupSql = ValueIfNull
Else
LookupSql = Nz(.Fields(Index), ValueIfNull)
End If
.Close
End With
Set rst = Nothing
ExitHere:
Exit Function
HandleErr:
If Not (rst Is Nothing) Then
rst.Close
Set rst = Nothing
End If
Err.Raise Err.Number, "LookupSQL:" & Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End Function